PHP Data Objects: Error Handling

Exclusive offer: get 50% off this eBook here
Learning PHP Data Objects

Learning PHP Data Objects — Save 50%

A Beginner's Guide to PHP Data Objects, Database Connection Abstraction Library for PHP 5

$23.99    $12.00
by Dennis Popel | July 2008 | MySQL Open Source PHP

Most web applications have rather simple error handling strategy. When an error occurs, the script terminates and an error page is presented. The error should be logged in the error log, and the developers or maintainers should check the logs periodically. In this article by Dennis Popel, we will look through the most common sources of errors in database-driven web applications.

  • Server software failure or overload such as the famous "too many connections" error
  • Inappropriate configuration of the application, which may happen when we use an incorrect connection string, a rather common mistake when an application is moved from one host to another.

In this article, we will extend our application so that we can edit existing records as well as add new records. As we will deal with user input supplied via web forms, we have to take care of its validation. Also, we may add error handling so that we can react to non-standard situations and present the user with a friendly message.

Before we proceed, let's briefly examine the sources of errors mentioned above and see what error handling strategy should be applied in each case. Our error handling strategy will use exceptions, so you should be familiar with them. If you are not, you can refer to Appendix A, which will introduce you to the new object-oriented features of PHP5.

We have consciously chosen to use exceptions, even though PDO can be instructed not to use them, because there is one situation where they cannot be avoided. The PDO constructors always throw an exception when the database object cannot be created, so we may as well use exceptions as our main error‑trapping method throughout the code.

Sources of Errors

To create an error handling strategy, we should first analyze where errors can happen. Errors can happen on every call to the database, and although this is rather unlikely, we will look at this scenario. But before doing so, let's check each of the possible error sources and define a strategy for dealing with them.

This can happen on a really busy server, which cannot handle any more incoming connections. For example, there may be a lengthy update running in the background. The outcome is that we are unable to get any data from the database, so we should do the following.

If the PDO constructor fails, we present a page displaying a message, which says that the user's request could not be fulfilled at this time and that they should try again later. Of course, we should also log this error because it may require immediate attention. (A good idea would be emailing the database administrator about the error.)

The problem with this error is that, while it usually manifests itself before a connection is established with the database (in a call to PDO constructor), there is a small risk that it can happen after the connection has been established (on a call to a method of the PDO or PDO Statement object when the database server is being shutdown). In this case, our reaction will be the same—present the user with an error message asking them to try again later.

Improper Configuration of the Application

This error can only occur when we move the application across servers where database access details differ; this may be when we are uploading from a development server to production server, where database setups differ. This is not an error that can happen during normal execution of the application, but care should be taken while uploading as this may interrupt the site's operation.

If this error occurs, we can display another error message like: "This site is under maintenance". In this scenario, the site maintainer should react immediately, as without correcting, the connection string the application cannot normally operate.

Improper Validation of User Input

This is an error which is closely related to SQL injection vulnerability. Every developer of database-driven applications must undertake proper measures to validate and filter all user inputs. This error may lead to two major consequences: Either the query will fail due to malformed SQL (so that nothing particularly bad happens), or an SQL injection may occur and application security may be compromised. While their consequences differ, both these problems can be prevented in the same way.

Let's consider the following scenario. We accept some numeric value from a form and insert it into the database. To keep our example simple, assume that we want to update a book's year of publication. To achieve this, we can create a form that has two fields: A hidden field containing the book's ID, and a text field to enter the year. We will skip implementation details here, and see how using a poorly designed script to process this form could lead to errors and put the whole system at risk.

The form processing script will examine two request variables:$_REQUEST['book'], which holds the book's ID and $_REQUEST['year'], which holds the year of publication. If there is no validation of these values, the final code will look similar to this:

$book = $_REQUEST['book'];
$year = $_REQUEST['year'];
$sql = "UPDATE books SET year=$year WHERE id=$book";
$conn->query($sql);

Let's see what happens if the user leaves the book field empty. The final SQL would then look like:

UPDATE books SET year= WHERE id=1;

This SQL is malformed and will lead to a syntax error. Therefore, we should ensure that both variables are holding numeric values. If they don't, we should redisplay the form with an error message.

Now, let's see how an attacker might exploit this to delete the contents of the entire table. To achieve this, they could just enter the following into the year field:

2007; DELETE FROM books;

This turns a single query into three queries:

UPDATE books SET year=2007; DELETE FROM books; WHERE book=1;

Of course, the third query is malformed, but the first and second will execute, and the database server will report an error. To counter this problem, we could use simple validation to ensure that the year field contains four digits. However, if we have text fields, which can contain arbitrary characters, the field's values must be escaped prior to creating the SQL.

Inserting a Record with a Duplicate Primary Key or Unique Index Value

This problem may happen when the application is inserting a record with duplicate values for the primary key or a unique index. For example, in our database of authors and books, we might want to prevent the user from entering the same book twice by mistake. To do this, we can create a unique index of the ISBN column of the books table. As every book has a unique ISBN, any attempt to insert the same ISBN will generate an error. We can trap this error and react accordingly, by displaying an error message asking the user to correct the ISBN or cancel its addition.

Syntax Errors in SQL Statements

This error may occur if we haven't properly tested the application. A good application must not contain these errors, and it is the responsibility of the development team to test every possible situation and check that every SQL statement performs without syntax errors.

If this type of an error occurs, then we trap it with exceptions and display a fatal error message. The developers must correct the situation at once.

Now that we have learned a bit about possible sources of errors, let's examine how PDO handles errors.

Types of Error Handling in PDO

By default, PDO uses the silent error handling mode. This means that any error that arises when calling methods of the PDO or PDOStatement classes go unreported. With this mode, one would have to call PDO::errorInfo(), PDO::errorCode(), PDOStatement::errorInfo(), or PDOStatement::errorCode(), every time an error occurred to see if it really did occur. Note that this mode is similar to traditional database access—usually, the code calls mysql_errno(),and mysql_error() (or equivalent functions for other database systems) after calling functions that could cause an error, after connecting to a database and after issuing a query.

Another mode is the warning mode. Here, PDO will act identical to the traditional database access. Any error that happens during communication with the database would raise an E_WARNING error. Depending on the configuration, an error message could be displayed or logged into a file.

Finally, PDO introduces a modern way of handling database connection errors—by using exceptions. Every failed call to any of the PDO or PDOStatement methods will throw an exception.

As we have previously noted, PDO uses the silent mode, by default. To switch to a desired error handling mode, we have to specify it by calling PDO::setAttribute() method. Each of the error handling modes is specified by the following constants, which are defined in the PDO class:

  • PDO::ERRMODE_SILENT – the silent strategy.
  • PDO::ERRMODE_WARNING – the warning strategy.
  • PDO::ERRMODE_EXCEPTION – use exceptions.

To set the desired error handling mode, we have to set the PDO::ATTR_ERRMODE attribute in the following way:

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

To see how PDO throws an exception, edit the common.inc.php file by adding the above statement after the line #46. If you want to test what will happen when PDO throws an exception, change the connection string to specify a nonexistent database. Now point your browser to the books listing page.

You should see an output similar to:

PHP Data Objects: Error Handling

This is PHP's default reaction to uncaught exceptions—they are regarded as fatal errors and program execution stops. The error message reveals the class of the exception, PDOException, the error description, and some debug information, including name and line number of the statement that threw the exception. Note that if you want to test SQLite, specifying a non-existent database may not work as the database will get created if it does not exist already. To see that it does work for SQLite, change the $connStr variable on line 10 so that there is an illegal character in the database name:

$connStr = 'sqlite:/path/to/pdo*.db';

Refresh your browser and you should see something like this:

PHP Data Objects: Error Handling

As you can see, a message similar to the previous example is displayed, specifying the cause and the location of the error in the source code.

Defining an Error Handling Function

If we know that a certain statement or block of code can throw an exception, we should wrap that code within the try…catch block to prevent the default error message being displayed and present a user-friendly error page. But before we proceed, let's create a function that will render an error message and exit the application. As we will be calling it from different script files, the best place for this function is, of course, the common.inc.php file.

Our function, called showError(), will do the following:

  • Render a heading saying "Error".
  • Render the error message. We will escape the text with the htmlspecialchars() function and process it with the nl2br() function so that we can display multi-line messages. (This function will convert all line break characters to tags.)
  • Call the showFooter() function to close the opening and tags. The function will assume that the application has already called the showHeader() function. (Otherwise, we will end up with broken HTML.)

We will also have to modify the block that creates the connection object in common.inc.php to catch the possible exception. With all these changes, the new version of common.inc.php will look like this:

<?php
/**
* This is a common include file
* PDO Library Management example application
* @author Dennis Popel
*/
// DB connection string and username/password
$connStr = 'mysql:host=localhost;dbname=pdo';
$user = 'root';
$pass = 'root';
/**
* This function will render the header on every page,
* including the opening html tag,
* the head section and the opening body tag.
* It should be called before any output of the
/**
* This function will 'close' the body and html
* tags opened by the showHeader() function
*/
function showFooter()
{
?>
</body>
</html>
<?php
}
/**
* This function will display an error message, call the
* showFooter() function and terminate the application
* @param string $message the error message
*/
function showError($message)
{
echo "<h2>Error</h2>";
echo nl2br(htmlspecialchars($message));
showFooter();
exit();
}
// Create the connection object
try
{
$conn = new PDO($connStr, $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
showHeader('Error');
showError("Sorry, an error has occurred. Please try your request
latern" . $e->getMessage());
}

As you can see, the newly created function is pretty straightforward. The more interesting part is the try…catch block that we use to trap the exception. Now with these modifications we can test how a real exception will get processed. To do that, make sure your connection string is wrong (so that it specifies wrong databasename for MySQL or contains invalid file name for SQLite). Point your browser to books.php and you should see the following window:

PHP Data Objects: Error Handling

Learning PHP Data Objects A Beginner's Guide to PHP Data Objects, Database Connection Abstraction Library for PHP 5
Published: August 2007
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Creating the Edit Book Page

As we have discussed earlier, we want to extend our application so that we can add and edit books and authors. Also, our system should be able to protect us from entering the same book twice—by enforcing the unique index on the ISBN column in the books table.

Before we proceed with the code, we will create the index. Fire up your command line client and enter the following command (which is the same for MySQL and SQLite):

CREATE UNIQUE INDEX idx_isbn ON books(isbn);

We will also make our edit book page serve two purposes at once—adding a new book and editing an existing one. The script will distinguish which action to take by the presence of the book ID, either in an URL or in a hidden form field. We will link to this new page from within books.php, so that we will be able to edit every book just by clicking on a link on the books listing page.

This page is more complicated, so I will provide you with the code first and then discuss it. Let's call this page edit Book.php:

* @author Dennis Popel
*/
// Don't forget the include
include('common.inc.php');
// See if we have the book ID passed in the request
$id = (int)$_REQUEST['book'];
if($id) {
// We have the ID, get the book details from the table
$q = $conn->query("SELECT * FROM books WHERE id=$id");
$book = $q->fetch(PDO::FETCH_ASSOC);
$q->closeCursor();
$q = null;
}
else {
// We are creating a new book
$book = array();
}
// Now get the list of all authors' first and last names
// We will need it to create the dropdown box for author
$authors = array();
$q = $conn->query("SELECT id, lastName, firstName FROM authors ORDER
BY lastName, firstName");
$q->setFetchMode(PDO::FETCH_ASSOC);
while($a = $q->fetch())
{
$authors[$a['id']] = "$a[lastName], $a[firstName]";
}
// Now see if the form was submitted
if($_POST['submit']) {
// Validate every field
$warnings = array();
// Title should be non-empty
if(!$_POST['title'])
{
$warnings[] = 'Please enter book title';
}
// Author should be a key in the $authors array
if(!array_key_exists($_POST['author'], $authors))
{
$warnings[] = 'Please select author for the book';
}
// ISBN should be a 10-digit number
if(!preg_match('~^d{10}$~', $_POST['isbn'])) {
$warnings[] = 'ISBN should be 10 digits';
}
// Published should be non-empty
if(!$_POST['publisher']) {
$warnings[] = 'Please enter publisher';
}
// Year should be 4 digits
if(!preg_match('~^d{4}$~', $_POST['year'])) {
$warnings[] = 'Year should be 4 digits';
}
// Sumary should be non-empty
if(!$_POST['summary']) {
$warnings[] = 'Please enter summary';
}
// If there are no errors, we can update the database
// If there was book ID passed, update that book
if(count($warnings) == 0) {
if(@$book['id']) {
$sql = "UPDATE books SET title=" . $conn>quote($_POST['title']) .
', author=' . $conn->quote($_POST['author']) .
', isbn=' . $conn->quote($_POST['isbn']) .
', publisher=' . $conn->quote($_POST['publisher']) .
', year=' . $conn->quote($_POST['year']) .
', summary=' . $conn->quote($_POST['summary']) .
" WHERE id=$book[id]";
}
else {
$sql = "INSERT INTO books(title, author, isbn, publisher,
year,summary) VALUES(" .
$conn->quote($_POST['title']) .
', ' . $conn->quote($_POST['author']) .
', ' . $conn->quote($_POST['isbn']) .
', ' . $conn->quote($_POST['publisher']) .
', ' . $conn->quote($_POST['year']) .
', ' . $conn->quote($_POST['summary']) .
')';
}
// Now we are updating the DB.
// We wrap this into a try/catch block
// as an exception can get thrown if
// the ISBN is already in the table
try
{
$conn->query($sql);
// If we are here that means that no error
// We can return back to books listing
header("Location: books.php");
exit;
}
catch(PDOException $e)
{
$warnings[] = 'Duplicate ISBN entered. Please correct';
}
}
}
else {
// Form was not submitted.
// Populate the $_POST array with the book's details
$_POST = $book;
}
// Display the header
showHeader('Edit Book');
// If we have any warnings, display them now
if(count($warnings)) {
echo "<b>Please correct these errors:</b><br>";
foreach($warnings as $w)
{
echo "- ", htmlspecialchars($w), "<br>";
}
}
// Now display the form
?>
<form action="editBook.php" method="post">
<table border="1" cellpadding="3">
<tr>
<td>Title</td>
<td>
<input type="text" name="title"
value="<?=htmlspecialchars($_POST['title'])?>">
</td>
</tr>
<tr>
<td>Author</td>
<td>
<select name="author">
<option value="">Please select...</option>
<?php foreach($authors as $id=>$author) { ?>
<option value="<?=$id?>"
<?= $id == $_POST['author'] ? 'selected' : ''?>>
<?=htmlspecialchars($author)?>
</option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>ISBN</td>
<td>
<input type="text" name="isbn"
value="<?=htmlspecialchars($_POST['isbn'])?>">
</td>
</tr>
<tr>
<td>Publisher</td>
<td>
<input type="text" name="publisher"
value="<?=htmlspecialchars($_POST['publisher'])?>">
</td>
</tr>
<tr>
<td>Year</td>
<td>
<input type="text" name="year"
value="<?=htmlspecialchars($_POST['year'])?>">
</td>
</tr>
<tr>
<td>Summary</td>
<td>
<textarea name="summary"><?=htmlspecialchars(
$_POST['summary'])?></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="Save">
</td>
</tr>
</table>
<?php if(@$book['id']) { ?>
<input type="hidden" name="book" value="<?=$book['id']?>">
<?php } ?>
</form>
<?php
// Display footer
showFooter();

The code is rather self-documenting, but let's briefly go through its main parts. Lines 12 to 23 deal with fetching the book details would be edited if the page was requested with the book ID. These details are stored in the $book variable. Note how we explicitly cast the request parameter book to integer so that no SQL injection can occur (line 13). If no book ID is provided, we set it to an empty array. Note how we call the closeCursor() function and then assign the $q variable to null. This is necessary as we are going to reuse the connection object.

Lines 26 to 33 prepare the list of authors. As our system allows exactly one author per book, we will create a select box field listing all the authors.

Line 35 checks whether there was a submission of the form. If the test is successful, the script validates every field (lines 37 to 68). Every failed validation is appended to a list of warnings. (The $warnings variable is initialized with an empty array.) We will use this list to see whether validations were successful and to store error messages if they weren't.

Lines 69 to 94 build the actual SQL for update. The final SQL depends on whether we are updating a book (when the $book array will contain the id key), or adding a new one. Note how we quote every column value prior to query execution.

Lines 95 to 112 try to execute the query. It may fail if the user has entered a duplicate ISBN so we wrap the code in a try…catch block. If an exception does get thrown, the catch block will append the corresponding warning to the $warnings array. If everything works without an error, the script redirects to the books listing page where you should see the changes.

Lines 113 to 118 get executed if there was no submission of the form. Here the $_POST array gets populated with the contents of the $books variable. We do this because we will use the $_POST array to display form fields' values later in the code.

Note how we display error messages (if any) on lines 122 to 129 and the select box on lines 141 to 154. (We are looking through all authors and if the author's ID matches this book author's ID then that author is marked as the selected option.) Also, the other form fields are rendered using the htmlspecialchars() function applied to the items of the $_POST array. Lines 189 to 191 will add a hidden field to the form that contains the ID of the currently edited book (if any).

Modern web applications employ client-side validation in addition to server-side validation of user-supplied data. Though this is not in the scope of this book, you might consider browser-based validation in your projects to increase responsiveness and potentially decrease load of your web server.

Now, we should link to the newly created page from the books.php page. We will provide an Edit this book link for every listed book as well as an Add book link under the table. I will not reproduce the whole books.php source here, just the lines that should be changed. So, lines 32 to 48 should be replaced with the following:

<?php
// Now iterate over every row and display it
while($r = $q->fetch())
{
?>
<tr>
<td><ahref="author.php?id=<?=$r['authorId']?>">
<?=htmlspecialchars("$r[firstName] $r[lastName]")?></a></td>
<td><?=htmlspecialchars($r['title'])?></td>
<td><?=htmlspecialchars($r['isbn'])?></td>
<td><?=htmlspecialchars($r['publisher'])?></td>
<td><?=htmlspecialchars($r['year'])?></td>
<td><?=htmlspecialchars($r['summary'])?></td>
<td>
<a href="editBook.php?book=<?=$r['id']?>">Edit</a>
</td>
</tr>
<?php
}
?>
<a href="editBook.php">Add book...</a>
<?php
// Display footer
showFooter();

The following should be added just before the call to the showFooter() function so that the four lines look like this:

Now, if you again navigate to the books.php page you should see the following window:

PHP Data Objects: Error Handling

 

To see how our edit book page looks, click on any Edit link in the last column of the table. You should see the following form:

 

PHP Data Objects: Error Handling

Let's see how our form works. It is validating every form field that gets sent to the database. If there is any validation error, the form will not update the database and prompt the user to correct his submission. For example, try changing the author select box to the default option (labeled Please select…) and editing the ISBN to be 5 digits long.

If you click the Save button, you should see that the form displays followingerror messages:

PHP Data Objects: Error Handling

Now correct the errors and try to change the ISBN to 1904811027. This ISBN is already used in our database by another book, so the form will again display an error. You can further test the form by adding a book. You might also want to test how it works with SQLite.

Creating the Edit Author Page

Our application still lacks the add/edit author functionality. This page will be somewhat simpler than the edit book page because it will not have the select box for authors and no unique index. (You may want to create a unique index on the author's first and last name columns to prevent duplicates there too, but we will leave this up to you). Let's call this page editAuthor.php. Here is its source code:

<?php
/**
* This page allows to add or edit an author
* PDO Library Management example application
* @author Dennis Popel
*/
// Don't forget the include
include('common.inc.php');
// See if we have the author ID passed in the request
$id = (int)$_REQUEST['author'];
if($id) {
// We have the ID, get the author details from the table
$q = $conn->query("SELECT * FROM authors WHERE id=$id");
$author = $q->fetch(PDO::FETCH_ASSOC);
$q->closeCursor();
$q = null;
}
else {
// We are creating a new book
$author = array();
}
// Now see if the form was submitted
if($_POST['submit']) {
// Validate every field
$warnings = array();
// First name should be non-empty
if(!$_POST['firstName']) {
$warnings[] = 'Please enter first name';
}
// Last name should be non-empty
if(!$_POST['lastName']) {
$warnings[] = 'Please enter last name';
}
// Bio should be non-empty
if(!$_POST['bio']) {
$warnings[] = 'Please enter bio';
}
// If there are no errors, we can update the database
// If there was book ID passed, update that book
if(count($warnings) == 0) {
if(@$author['id']) {
$sql = "UPDATE authors SET firstName=" .
$co>quote($_POST['firstName']) .
', lastName=' . $conn->quote($_POST['lastName']) .
', bio=' . $conn->quote($_POST['bio']) .
" WHERE id=$author[id]";
}
else {
$sql = "INSERT INTO authors(firstName, lastName, bio) VALUES(" .
$conn->quote($_POST['firstName']) .
', ' . $conn->quote($_POST['lastName']) .
', ' . $conn->quote($_POST['bio']) .
')';
}
$conn->query($sql);
header("Location: authors.php");
exit;
}
}
else {
// Form was not submitted.
// Populate the $_POST array with the author's details
$_POST = $author;
}
// Display the header
showHeader('Edit Author');
// If we have any warnings, display them now
if(count($warnings)) {
echo "<b>Please correct these errors:</b><br>";
foreach($warnings as $w)
{
echo "- ", htmlspecialchars($w), "<br>";
}
}
// Now display the form
?>
<form action="editAuthor.php" method="post">
<table border="1" cellpadding="3">
<tr>
<td>First name</td>
<td>
<input type="text" name="firstName"
value="<?=htmlspecialchars($_POST['firstName'])?>">
</td>
</tr>
<tr>
<td>Last name</td>
<td>
<input type="text" name="lastName"
value="<?=htmlspecialchars($_POST['lastName'])?>">
</td>
</tr>
<tr>
<td>Bio</td>
<td>
<textarea name="bio"><?=htmlspecialchars($_POST['bio'])?>
</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="Save">
</td>
</tr>
</table>
<?php if(@$author['id']) { ?>
<input type="hidden" name="author" value="<?=$author['id']?>">
<?php } ?>
</form>
<?php
// Display footer
showFooter();

This source is built in the same way as the editBook.php page so you should be able to follow it easily.

We will link to the editAuthors.php page in the same way as we linked to the editBook.php page from the books.php, page. Edit the authors.php file and change lines 30-41 to the following:

while($r = $q->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?=htmlspecialchars($r['firstName'])?></td>
<td><?=htmlspecialchars($r['lastName'])?></td>
<td><?=htmlspecialchars($r['bio'])?></td>
<td>
<a href="editAuthor.php?author=<?=$r['id']?>">Edit</a>
</td>
</tr>
<?php
}

Add the following line just before the last PHP block:

<a href="editAuthor.php">Add Author...</a>

Now, if you refresh the authors.php page you will see the following:

PHP Data Objects: Error Handling

You can click the Edit links in the rightmost column to edit every author's details. You can try submitting the form with empty values to see that invalid submissions will be rejected. Also, you can try and add a new author to the system. After you successfully do this, you may want to go back to books listing and edit some book. You will see that newly created author is available in the authors select box.

Securing against Uncaught Exceptions

As we have seen previously, we place the try...catch blocks around code that can throw exceptions. However, in very rare cases, there might be some unexpected exceptions. We can imitate such an exception by modifying one of the queries so that it contains some malformed SQL. For example, let's edit authors.php, line 16 to the following:

$q = $conn->query("SELECT * FROM authors ORDER BY lastName,
firstName");

Now try to navigate to authors.php with your browser to see that an uncaught exception has occurred. To correctly handle this situation, we either should create an exception handler or wrap every block of code that calls PDO or PDOStatement class methods in a try…catch block.

Let's see how we can create the exception handler. This is an easier approach as it does not require changing lots of code. However, for big applications this may be bad practice as handling exceptions, where they occur may be more secure and better recovery logic can be applied.

However, with our simple application we can use the global exception handler. It will just use the showError() function to say that the site is under maintenance:

/**
* This is the default exception handler
* @param Exception $e the uncaught exception
*/
function exceptionHandler($e)
{
showError("Sorry, the site is under maintenancen" .
$e->getMessage());
}
// Set the global excpetion handler
set_exception_handler('exceptionHandler');

Place this into common.inc.php, just before the connection creation code block. If you refresh the authors.php page now, you will see that the handler gets called.

It is always a good idea to have the default exception handler. As you have noticed, unhandled exceptions expose too much sensitive information including database connection details. Also, in real world applications the error pages should not display any information about the type of the error. (Note that our example application does.) The default handler should write to the error log and alert site maintainers about the error.

Learning PHP Data Objects A Beginner's Guide to PHP Data Objects, Database Connection Abstraction Library for PHP 5
Published: August 2007
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Summary

In this article, we examined how PDO handles errors and introduced exceptions. Also,we investigated the sources of errors and saw how to counter them.

Our sample application was extended with some real-world administration functionality that uses data validation and is secured against SQL injection attacks. Of course, they should also allow database modifications only to certain users based on login names and passwords. However, this is beyond the scope of this book.

About the Author :


Dennis Popel

Dennis Popel is an experienced PHP/PHP5 developer currently working for an Australian web development company, Motive Media (www.motivemedia.com.au). Serving Sun Microsystems Australia, Luna Park Sydney, Alsco Holdings and Pine Solutions, amongst others, Dennis leads company development of proprietary, web-based, software solutions. In his spare time, he runs the onPHP5.com blog and works on an online RSS aggregator NewzMix.

Dennis Popel has been developing with PHP for more than 5 years and is experienced in such fields as object-oriented design and MVC.

Previously he has worked at Rapid Intelligence, another Australian-based web company, publisher of such popular titles as NationMaster.com, FactBites.com and Qwika.com. In the past, Dennis was developing proprietary Java applications.

This book is devoted to all the people that introduced and guided me in this wonderful world of information technology.

Books From Packt

Building Websites with Joomla! 1.5
Building Websites with Joomla! 1.5

Drupal 5 Themes
Drupal 5 Themes

PHPEclipse: A User Guide
PHPEclipse: A User Guide

PHP 5 CMS Framework Development
PHP 5 CMS Framework Development

WordPress Complete
WordPress Complete

Configuring IPCop Firewalls: Closing Borders with Open Source
Configuring IPCop Firewalls: Closing Borders with Open Source

Google Web Toolkit GWT Java AJAX Programming
Google Web Toolkit GWT Java AJAX Programming

Mastering phpMyAdmin 2.11 for Effective MySQL Management
Mastering phpMyAdmin 2.11 for Effective MySQL Management

 


 

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
h
N
n
2
y
n
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software