Page 402 - Beginning PHP 5.3
P. 402
Part III: Using PHP in Practice
Next, the script uses PDO to open the database connection, trapping and displaying any error that
occurs:
try {
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo “Connection failed: “ . $e->getMessage();
}
Now the SQL query is created and stored in a string variable, $sql. This query simply extracts all the
data from the fruit table:
$sql = “SELECT * FROM fruit“;
The main part of the script runs the query, and loops through the returned rows of data, displaying the
contents of each row in an HTML li element:
echo “<ul>“;
try {
$rows = $conn->query( $sql );
foreach ( $rows as $row ) {
echo “<li>A “ . $row[“name“] . “ is “ . $row[“color“] . “</li>“;
}
} catch ( PDOException $e ) {
echo “Query failed: “ . $e->getMessage();
}
echo “</ul>“;
Notice that both the call to $conn->query and the looping code are within a try block to catch any
exceptions that might be caused by running the query. If an exception is thrown, it is handled by the
catch block, which displays the message “Query failed,” along with the error message.
Finally, the script closes the database connection and completes the XHTML page:
$conn = null;
?>
</body>
</html>
That’s the basics of using PDO to connect to a database from within your PHP scripts. In the next couple
of chapters you use PHP to build more advanced queries and commands for manipulating your data,
and construct some useful database-driven applications.
364
9/21/09 9:11:15 AM
c12.indd 364 9/21/09 9:11:15 AM
c12.indd 364