< All PHP topicsPHP (3)Perl (3)

Mysql Database Programming

Writing scripts and applications to hand data from and for a MySQL database.

PHP:

MySQL is no longer included with PHP, and must be downloaded seperately. Methods and install information:

http://uk3.php.net/mysql

Connect to a database

Last updated at 12:56 AM on Monday 16th July, 2007 by Isaac Turner


Connect to the database

mysql_connect($host, $user, $password)
  or die('Could not connect to database (' . $user . '@' . $host . '): ' . mysql_error());

Select the database

mysql_select_db($db_name)
  or die('Could not select database');

Comments (0)

Run query

Last updated at 01:03 AM on Monday 16th July, 2007 by Isaac Turner


If the query just alters data without returning data rows, the query can be handled thus:

$query = "UPDATE table_name " .
         "SET time=NOW() WHERE id=12";

mysql_query($query)
  or die('<h1>Query failed</h1><br />' . mysql_error() . '<br />' . $query);

However if rows of data are being fetched from the database, the following is standard practice in PHP.

$query = "SELECT id, time FROM table_name";

$result = mysql_query($query)
  or die('<h1>Query failed</h1><br />' . mysql_error() . '<br />' . $query);

while($row = mysql_fetch_assoc($result))
  echo $row['id'] . '->' . $row['time'] . "<br />\n";

mysql_free_result($result);

Comments (0)

Close Database Connection

Last updated at 01:32 AM on Saturday 10th May, 2008 by Isaac Turner


To clear out resources used by a query:

mysql_free_result($query);

In PHP it is not necessary to clean up after you are finished using a database. This is because when the program exits it disconnects from the database and closes the connection to the mysql server automatically as part of the clean up. However, if you want to connect to another mysql server or wish to keep tidy code, you may use the mysql_close()[uk.php.net] function to disconnect from the mysql server.

mysql_close($db);

Comments (0)