SELECT - Running Database Queries

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 script below shows you how to run a query to get the last 10 rows of the Comment table:

#- MySQL-Select-Query.php
#- Copyright (c) 2015,, All Rights Reserved.
  $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");


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.

Last update: 2015.

Table of Contents

 About This Book

 PHP Installation on Windows Systems

 Integrating PHP with Apache Web Server

 charset="*" - Encodings on Chinese Web Pages

 Chinese Characters in PHP String Literals

 Multibyte String Functions in UTF-8 Encoding

 Input Text Data from Web Forms

 Input Chinese Text Data from Web Forms

 MySQL - Installation on Windows

MySQL - Connecting PHP to Database

 php_mysql.dll - Configuring PHP to Use MySQL Module

 Commonly Used MySQL Functions

 mysql_connect() - Creating MySQL Connections

 INSERT INTO - Inserting New Records

SELECT - Running Database Queries

 UPDATE - Modifying Database Records

 MySQL - Character Set and Encoding

 MySQL - Sending Non-ASCII Text to MySQL

 Retrieving Chinese Text from Database to Web Pages

 Input Chinese Text Data to MySQL Database


 PDF Printing Version