Entry
How do I send values to a mySQL database?
Mar 19th, 2008 22:41
ha mo, Philip Olson, Bruce de Mink,
By using the mysql_query() function. PHP has little to do with this
except providing an API to MySQL so you can then run queries with one
type of query being an INSERT statement.
First construct your query, here's an example query:
INSERT INTO sometable (col1, col2) VALUES ('example','more data');
This assumes you have a table named sometable with columns named col1
and col2. This would insert the value 'example' into col1, and 'more
data' into col2. Another example:
INSERT INTO sometable (col1,col2) VALUES ('$name','$email');
That inserts the value of $name into col1, and the value of $email into
col2. These values can come from anywhere. Now let's go into more
detail:
// First connect and select our database, if there are problems
// let's print some basic debugging info
$conn = @mysql_connect('localhost', 'myusername', 'mypass');
if (!$conn) {
echo "Could not connect to DB: " . mysql_error();
exit;
}
if (!@mysql_select_db('dbname', $conn)) {
echo "Could not select DB: " . mysql_error();
exit;
}
// See also the magic_quotes_gpc PHP directive, if it's on you should
// not run addslashes() on Get, Post, or Cookie data.
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
// If we make it here we know we're connected, let's run a query
$sql = "INSERT INTO sometable (name,email) VALUES ('$name','$email')";
// Remember mysql_query() returns false if the query could not
// be executed.
$result = @mysql_query($sql, $conn);
if (!$result) {
echo "Could not run query ($sql): " . mysql_error();
exit;
}
// If we make it here we know the query ran, which is good
echo "Query ($query) was executed!";
The above is just a basic example, you of course should not send data
like sql queries to users, it's only for debugging. It should
demonstrate that PHP simply allows you to execute queries so you
construct your own query and execute it.
See also: http://www.php.net/function.mysql-query
http://www.tantofa.com
http://www.fantofa.com
http://www.mantofa.com
http://www.tanpola.com
http://www.tampola.com
http://www.yamot.com
http://www.mozmar.com
http://www.templatestemp.com