Sending SQL Queries with PHP
In Chapter 2, Getting Started with MySQL, 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 joke table we created in Chapter 2, Getting Started with MySQL:
$sql = 'CREATE TABLE joke (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
joketext TEXT,
jokedate DATE NOT NULL
)';
if (@mysql_query($sql)) {
echo '<p>joke table successfully created!</p>';
} else {
exit('<p>Error creating joke 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 , Getting Started with MySQL to set the dates of all jokes that contained the word "chicken":
$sql = "UPDATE joke SET jokedate='1994-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 {
exit('<p>Error performing update: ' . mysql_error() .
'</p>');
}
SELECT queries are treated a little differently, as they can retrieve a lot of data, and PHP must provide ways to handle that information.
Handling SELECT Result Sets
For most SQL queries, the mysql_query function returns either true (success) or false (failure). For SELECT queries, this just isn't enough. You'll recall that SELECT queries are used to view stored data in the database. In addition to indicating whether the query succeeded or failed, PHP must also receive the results of the query. Thus, when it processes a SELECT query, mysql_query returns a number that identifies a result set, which contains a list of all the rows (entries) returned from the query. False is still returned if the query fails for any reason.
$result = @mysql_query('SELECT JokeText FROM Jokes');
if (!$result) {
exit('<p>Error performing query: ' . mysql_error() .
'</p>');
}
Provided that no error was encountered in processing the query, the above code will place a number into the variable $result. This number corresponds to a result set that contains the text of all the jokes stored in the joke table. As there's no practical limit on the number of jokes in the database, that result set can be pretty big.
We mentioned before that the while loop is a useful control structure for dealing with large amounts of data. Here's an outline of the code that will process the rows in a result set one at a time:
while ($row = mysql_fetch_array($result)) {
// process the row...
}
The condition for the while loop probably doesn't resemble the conditions you're used to, so let me explain how it works. Consider the condition as a statement all by itself:
$row = mysql_fetch_array($result);
The mysql_fetch_array function accepts a result set number as a parameter (stored in the $result variable in this case), and returns the next row in the result set as an array (see Chapter 3, Getting Started with PHP for a discussion of arrays). When there are no more rows in the result set, mysql_fetch_array instead returns false.
Now, the above statement assigns a value to the $row variable, but, at the same time, the whole statement itself takes on that same value. This is what lets you use the statement as a condition in the while loop. Since a while loop will keep looping until its condition evaluates to false, this loop will occur as many times as there are rows in the result set, with $row taking on the value of the next row each time the loop executes. All that's left to figure out is how to get the values out of the $row variable each time the loop runs.
Rows of a result set returned by mysql_fetch_array are represented as associative arrays. The indices are named after the table columns in the result set. If $row is a row in our result set, then $row['joketext'] is the value in the joketext column of that row. So here's what our while loop should look like if we want to print the text of all the jokes in our database:
while ($row = mysql_fetch_array($result)) {
echo '<p>' . $row['joketext'] . '</p>';
}
To summarize, here's the complete code of a PHP Web page that will connect to our database, fetch the text of all the jokes in the database, and display them in HTML paragraphs:
Example 4.1. jokelist.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Our List of Jokes</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php
// Connect to the database server
$dbcnx = @mysql_connect('localhost', 'root', 'mypasswd');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}
// Select the jokes database
if (!@mysql_select_db('ijdb')) {
exit('<p>Unable to locate the joke ' .
'database at this time.</p>');
}
?>
<p>Here are all the jokes in our database:</p>
<blockquote>
<?php
// Request the text of all the jokes
$result = @mysql_query('SELECT joketext FROM joke');
if (!$result) {
exit('<p>Error performing query: ' . mysql_error() . '</p>');
}
// Display the text of each joke in a paragraph
while ($row = mysql_fetch_array($result)) {
echo '<p>' . $row['joketext'] . '</p>';
}
?>
</blockquote>
</body>
</html>
Figure 4.2 shows what this page looks like once you've added a couple of jokes to the database.
Figure 4.2. All my best material—in one place!
Inserting Data into the Database
In this section, we'll see how we can use the tools at our disposal to allow site visitors to add their own jokes to the database. If you enjoy a challenge, you might want to try to figure this out on your own before you read any further. There is little new material in this section, but it's mostly just a sample application that incorporates everything we've learned so far.
If you want to let visitors to your site type in new jokes, you'll obviously need a form. Here's the code for a form that will fit the bill:
Example 4.2. jokes.php (excerpt)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label>Type your joke here:<br />
<textarea name="joketext" rows="10" cols="40">
</textarea></label><br />
<input type="submit" value="SUBMIT" />
</form>
Figure 4.3 shows what this form looks like in a browser.
Figure 4.3. Another nugget of comic genius is added to the database.
Another nugget of comic genius is added to the database.
As we've seen before, when submitted, this form will load the very same page (because we used the $_SERVER['PHP_SELF'] variable for the form's action attribute) with one difference: a variable will be attached to the request. The variable, joketext, will contain the text of the joke as typed into the text area, and will appear in the $_POST and $_REQUEST arrays created by PHP.
To insert the submitted joke into the database, we use mysql_query to run an INSERT query, using the value stored in $_POST['joketext'] to fill in the joketext column in the query:
Example 4.3. jokes.php (excerpt)
if (isset($_POST['joketext'])) {
$joketext = $_POST['joketext'];
$sql = "INSERT INTO joke SET
joketext='$joketext',
jokedate=CURDATE()";
if (@mysql_query($sql)) {
echo '<p>Your joke has been added.</p>';
} else {
echo '<p>Error adding submitted joke: ' .
mysql_error() . '</p>';
}
}
The one new trick in this example is shown in bold. The MySQL function CURDATE() is used here to assign the current date as the value of the jokedate column. MySQL actually has dozens of these functions, but we'll introduce them only as required. For a complete MySQL function reference, refer to Appendix B, MySQL Functions.
We now have the code that will allow a user to type a joke and add it to our database. All that remains is to slot it into our existing joke viewing page in a useful fashion. As most users will only want to view jokes, we don't want to mar our page with a big, ugly form unless the user expresses an interest in adding a new joke. For this reason, our application is well suited for implementation as a multipurpose page. Here's the full code:
Example 4.4. jokes.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The Internet Joke Database</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php if (isset($_GET['addjoke'])): // User wants to add a joke
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label>Type your joke here:<br />
<textarea name="joketext" rows="10" cols="40">
</textarea></label><br />
<input type="submit" value="SUBMIT" />
</form>
<?php else: // Default page display
// Connect to the database server
$dbcnx = @mysql_connect('localhost', 'root', 'mypasswd');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}
// Select the jokes database
if (!@mysql_select_db('ijdb')) {
exit('<p>Unable to locate the joke ' .
'database at this time.</p>');
}
// If a joke has been submitted,
// add it to the database.
if (isset($_POST['joketext'])) {
$joketext = $_POST['joketext'];
$sql = "INSERT INTO joke SET
joketext='$joketext',
jokedate=CURDATE()";
if (@mysql_query($sql)) {
echo '<p>Your joke has been added.</p>';
} else {
echo '<p>Error adding submitted joke: ' .
mysql_error() . '</p>';
}
}
echo '<p>Here are all the jokes in our database:</p>';
// Request the text of all the jokes
$result = @mysql_query('SELECT joketext FROM joke');
if (!$result) {
exit('<p>Error performing query: ' .
mysql_error() . '</p>');
}
// Display the text of each joke in a paragraph
while ($row = mysql_fetch_array($result)) {
echo '<p>' . $row['joketext'] . '</p>';
}
// When clicked, this link will load this page
// with the joke submission form displayed.
echo '<p><a href="' . $_SERVER['PHP_SELF'] .
'?addjoke=1">Add a Joke!</a></p>';
endif;
?>
</body>
</html>
Load this up and add a new joke or two to the database via your browser. The resulting page should look like Figure 4.4.
Figure 4.4. Look, Ma! No SQL!
There we go! With a single file that contains a little PHP code, we're able to view existing jokes in, and add new jokes to, our MySQL database.
Source:
http://www.sitepoint.com/artic...data-web/2