This section describes how to run database queries.
If you want to run a database query on the MySQL server, you should write a SQL SELECT statement,
and send it to the MySQL server for execution with the mysql_query() function, which will return
a result set object. After that you can call the mysql_fetch_array() function to loop through
all rows in the result set, and convert them into arrays for processing. When you are done with
the result set object, call the mysql_free_result() function to release associated resources.
The example PHP sctipt below shows you how to run a query to get the last 10 rows of the Comment table:
<?php #MySQL-Select-Query.php
# Copyright (c) 2007 by Dr. Herong Yang, http://www.herongyang.com/
#
$con = mysql_connect("localhost", "Herong", "TopSecret");
$ok = mysql_select_db("HerongDB", $con);
$sql = "SELECT * FROM Comment ORDER BY ID DESC LIMIT 0, 10";
$res = mysql_query($sql, $con);
while ($row = mysql_fetch_array($res)) {
print("\nRecord ID = ".$row['ID']."\n");
print(" Name: ".$row['Name']."\n");
print(" Comment: ".$row['Comment']."\n");
}
mysql_free_result($res);
mysql_close($con);
?>
The output confirms that the script is working correctly. I god the last records first upto 10 of them:
Record ID = 2
Name: Bob
Comment: The first database transaction I want to try is
to insert a new record to the Comment table.
Inserting a new record can be done by sending
a SQL INSERT INTO statement to the MySQL server
for execution with the mysql_query() function.
After that you can call the mysql_insert_id()
function to obtain the auto-incremented primary
key value of the inserted record.
Record ID = 1
Name: Herong
Comment: This is a test.