Page 399 - Beginning PHP 5.3
P. 399
Chapter 12: Introducing Databases and SQL
Now you can capture any error that might occur when connecting to the database by using a try ...
catch code block. If you were writing a sophisticated application, you ’ d probably log the error message
to a file, and possibly send an email to the Webmaster informing him of the details of the error. For the
sake of these examples, though, you ’ ll just display the error message in the Web page:
try {
$conn = new PDO( $dsn, $username, $password );
$conn- > setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo “Connection failed: “ . $e- > getMessage();
}
PHP runs the code within the try block. If an exception is raised by PDO, the catch block stores the
PDOException object in $e , then displays the error message with $e - > getMessage() .
For example, if the $password variable in the script contained an incorrect password, you ’ d see a
message like this appear when you ran the script:
Connection failed: SQLSTATE[28000] [1045] Access denied for user
‘root’@’localhost’ (using password: YES)
Reading Data
Now that you ’ ve connected to your database in your PHP script, you can read some data from the
database using a SELECT statement. To send SQL statements to the MySQL server, you use the query
method of the PDO object:
$conn- > query ( $sql );
If your SQL statement returns rows of data as a result set, you can capture the data by assigning the
result of $conn - > query to a variable:
$rows = $conn- > query ( $sql );
The result returned by $conn - > query is actually another type of object, called a PDOStatement object.
You can use this object along with a foreach loop to move through all the rows in the result set. Each
row is an associative array containing all the field names and values for that row in the table. For
example:
$sql = “SELECT * FROM fruit”;
$rows = $conn- > query( $sql );
foreach ( $rows as $row ) {
echo “name = “ . $row[“name”] . “ < br / > ”;
echo “color = “ . $row[“color”] . “ < br / > ”;
}
361
9/21/09 9:11:14 AM
c12.indd 361 9/21/09 9:11:14 AM
c12.indd 361