Sending SQL Queries with PHP - Page 3

January 24, 2002

In Chapter 2, we connected to the MySQL database server using a program called mysql that allowed us to type SQL queries (commands) and view the results of those queries immediately. In PHP, a similar mechanism exists: the mysql_query function.

mysql_query(query, connection_id);

Here query is a string that contains the SQL command we want to execute. As with mysql_select_db, the connection identifier parameter is optional.

What this function returns will depend on the type of query being sent. For most SQL commands, mysql_query returns either true or false to indicate success or failure respectively. Consider the following example, which attempts to create the Jokes table we created in Chapter 2:

$sql = "CREATE TABLE Jokes (
         JokeText TEXT,
         JokeDate DATE NOT NULL
if ( @mysql_query($sql) ) {
  echo("<p>Jokes table successfully created!</p>");
} else {
  echo("<p>Error creating Jokes table: " . mysql_error() . "</p>");

Again, we use the @ trick to suppress any error messages produced by mysql_query, and instead print out a friendlier error message of our own. The mysql_error function used here returns a string of text that describes the last error message that was sent by the MySQL server.

For DELETE, INSERT, and UPDATE queries (which serve to modify stored data), MySQL also keeps track of the number of table rows (entries) that were affected by the query. Consider the SQL command below, which we used in Chapter 2 to set the dates of all jokes that contained the word "chicken":

$sql = "UPDATE Jokes SET JokeDate='1990-04-01'
        WHERE JokeText LIKE '%chicken%'";

When we execute this query, we can use the mysql_affected_rows function to view the number of rows that were affected by this update:

if ( @mysql_query($sql) ) {
  echo("<p>Update affected " . mysql_affected_rows() . " rows.</p>");
} else {
  echo("<p>Error performing update: " . mysql_error() . "</p>");

SELECT queries are treated a little differently, since they can retrieve a lot of data, and PHP must provide ways to handle that information.