by Kevin Yank of SitePoint.com
Performing SQL Queries with PHP
In Part Two, 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>);
Where <query>
is a string containing the SQL command to be executed. As with mysql_select_db
, the connection identifier parameter is optional.
What this function returns depends 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 Part Two:
$sql = "CREATE TABLE Jokes ( " .
"ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " .
"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>");
}
The mysql_error
function used here returns a string of text describing 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 following SQL command, which we used in Part Two to set the dates of all jokes containing the word "chicken":
$sql = "UPDATE Jokes SET JokeDate='1990-04-01' " .
"WHERE JokeText LIKE '%chicken%'";
When executing 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 information, and PHP must provide ways of handling that information.
Handling SELECT Result Sets |
SitePoint.com is a fast growing Web Developer Community. Kevin Yank is the Editor of the SitePoint TechTimes, a fresh, technically oriented newsletter for the serious Webmaster. |