Databases, PHP

Database Error Handling

One of the aspects that separate the great coders from the rookies is not just making usable or working code but taking care of unforeseen eventualities. When working with more than one process (PHP and MySQL), sometimes unforeseen incompatibilities or server hiccups can cause an unwanted problem. To ensure the integrity of your web applications, it is important that, if such a problem occurs, the web application dies gracefully and provides a means for the developer to track the error.

Luckily, with the inclusion of exception handling in PHP 5, you can now create custom web applications that take care of their own errors. The following class uses exception handling to perform its error handling.

<?php
class mydb
{
    private $user;
    private $pass;
    private $host;
    private $db;

    // Constructor function.
    public function __construct()
    {
        $num_args = func_num_args();
        if ($num_args > 0) {
            $args = func_get_args();
            $this->host = $args[0];
            $this->user = $args[1];
            $this->pass = $args[2];
            $this->connect();
        }
    }

    // Function to connect to the database.
    private function connect()
    {
        try {
            if (!$this->db = mysql_connect($this->host, $this->user, $this->pass)) {
                $exceptionstring = "Error connection to database: <br />";
                $exceptionstring .= mysql_errno() . ": " . mysql_error();
                throw new Exception($exceptionstring);
            }
        } catch (Exception $e) {
            echo $e->getmessage();
        }
    }

    // Function to select a database.
    public function selectdb($thedb)
    {
        try {
            if (!mysql_select_db($thedb, $this->db)) {
                $exceptionstring = "Error opening database: $thedb: <br />";
                $exceptionstring .= mysql_errno() . ": " . mysql_error();
                throw new Exception($exceptionstring);
            }
        } catch (Exception $e) {
            echo $e->getmessage();
        }
    }

    // Function to perform a query.
    public function execute($thequery)
    {
        try {
            if (!mysql_query ($thequery, $this->db)) {
                $exceptionstring = "Error performing query: $thequery: <br />";
                $exceptionstring .= mysql_errno() . ": " . mysql_error();
                throw new Exception($exceptionstring);
            } else {
                echo "Query performed correctly: " . mysql_affected_rows()
                 . " rows affected.<br />";
            }
        } catch (Exception $e) {
            echo $e->getmessage();
        }
    }
    // Function to return a row set.
    public function getrows($thequery)
    {
        try {
            if (!$aquery = mysql_query ($thequery)) {
                $exceptionstring = "Error performing query: $thequery: <br />";
                $exceptionstring .= mysql_errno() . ": " . mysql_error();
                throw new Exception($exceptionstring);
            } else {
                $returnarr = array ();
                while ($adata = mysql_fetch_array($aquery)) {
                    $returnarr = array_merge($returnarr, $adata);
                }
                return $returnarr;
            }
        } catch (Exception $e) {
            echo $e->getmessage();
        }
    }
    // Function to close the database link.
    public function __destruct()
    {
        try {
            if (!mysql_close($this->db)) {
                $exceptionstring = "Error closing connection: <br />";
                $exceptionstring .= mysql_errno() . ": " . mysql_error();
                throw new Exception($exceptionstring);
            }
        } catch (Exception $e) {
            echo $e->getmessage();
        }
    }
} 

// Now, let's create an instance of mydb.
$mydb = new mydb("localhost", "apress", "testing");
// Now, you specify a database to use.
$mydb->selectdb("cds");
// Now, let's perform an action.
$adata = $mydb->execute("UPDATE cd SET title='Hybrid Theory' WHERE cdid='2'");
// Then, let's try to return a row set.
$adata = $mydb->getrows("SELECT * FROM cd ORDER BY cdid ASC");
for ($i = 0; $i < count ($adata); $i++) {
    echo $adata[$i] . "<br />";
}

As you can see, this database class (mydb) is completely validated by exception handling. Should anything go wrong when working with the database, the system will immediately run its exception handling capabilities and output a detailed error to help debug the situation. In the real world, you may want to consider showing users a polite message that says the website is down for maintenance (or something of the like) to alleviate any fears they may have. In a debug environment, however, this sort of code works rather well.

Note the mysql_error() function and the mysql_errno() function in this class; they will return the most recently generated error and error number (respectively) from the MySQL server. Using this sort of error handling can make debugging an application much more convenient.

Advertisements

One thought on “Database Error Handling

  1. “One of the aspects that separate the great coders from the rookies…” may be so

    but “One thing that separates really frustrating websites from less frustrating ones” is having really huge chunks of code with little horizontal scrollbars right at the bloody bottom

    ( nice elephant though )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s