Entry
I've got MySQL connected, what do I do next?
Aug 25th, 2005 12:55
Philip Olson, Jonathan Dean, Nathan Wallace,
You mean, you are connected to a MySQL server, right?
For you and anyone else a little confused by sql, here's the general
idea:
1) Connect to mysql server:
$conn = mysql_connect($hostname,$username,$password);
http://php.net/mysql-connect
2) Select a database:
$db = mysql_select_db($dbname,$conn);
http://php.net/mysql-select-db
3) Make a database query:
$sql = "SELECT id, name FROM users WHERE id = 42";
$result = mysql_query($query,$conn);
http://php.net/mysql-query
[ NOTE: There are different ways of retieving data, following,
is a simple way ]
4) Determine the number of rows:
$count_rows = mysql_num_rows($result);
http://php.net/mysql-num-rows
5) Retrieve row(s) of data (as an array):
$row = mysql_fetch_assoc($result);
echo $row['id'];
*OR* for multiple rows, use a loop:
while ($row = mysql_fetch_assoc($result) {
echo $row['id'];
}
http://php.net/mysql-fetch-assoc
6) Close current connection to mysql server:
mysql_close($conn);
http://php.net/mysql-close
Once again, this is just a simple example, not using any performance
features. The PHP Manual provides many more examples as do hundreds of
tutorials out there. Google for those tutorials.
If you get "undefined function" for any of the above code that means
your PHP does not have MySQL enabled. See the manual for details on how
to enable MySQL support for PHP.
Official Manual:
http://www.php.net/ref.mysql