End PHP Scripts Gracefully After a Failed Database Connection

Last week's post talked about externalizing the MySQL connection script for easier maintenance. The problem with the previous code is that it's not very user friendly. If the database connection fails, it just drops everything and displays an error. Well, there's probably other content on the web page that can be viewed without database access. The website navigation, for example, most likely doesn't require a database. The navigation will probably lead to other pages that don't need that database. To minimize the impact to the visitor, let's look at a more graceful solution for handling connection failures.

Building the Connection Script

The updated connection script will use extra variables which are more likely to conflict with variables throughout the rest of the web page. So we'll utilize a PHP class object to minimize risk. The class also helps tie the connection script to those extra variables.

<?php
class connect {
     //DECLARE PROPERTIES
     public $success        = false;
     public $errorText      = '';
     public $databaseObject = '';
 
     //CONSTRUCTOR
     public function __construct($endProgram=false) {
          //...
     }
}
?>

The class constructor is where the database connection happens. Note that we'll talk about the $endProgram flag later in the post.

<?php
class connect {
     //DECLARE PROPERTIES
     public $success        = false;
     public $errorText      = '';
     public $databaseObject = '';
 
     //CONSTRUCTOR
     public function __construct($endProgram=false) {
          //INITIALIZE VARIABLES
          $host     = 'yourhostname.com';
          $database = 'your_database_name';
          $username = 'your_username';
          $password = 'your_password';
 
          //IF THE DATABASE CONNECTION FAILS, FLAG ERROR
          $mysqli = new mysqli($host, $username, $password, $database);
          if($mysqli->connect_errno) {
               $this->errorText = 'There was a problem connecting to the database that this portion of the website requires to display properly.';
          } else {
               $this->databaseObject = $mysqli;
               $this->success        = true;
          }

     }
}
?>

The connection portion is similar to what we had before, except that it doesn't automatically display the error upon failure. It also flags whether a connection has been made which will be useful later. Since the example uses the object-oriented interface, we'll also need to reference the database object.

Now, the connection script just needs one more thing. The $endProgram flag, alluded to earlier, will mark pages which absolutely have no value without the database. For example, there may be a script that the website developer uses to maintain some aspect of the website. If that page doesn't do anything when the database is unavailable, we might as well prevent the whole page from running.

<?php
class connect {
     //...
 
          } else {
               $this->databaseObject = $mysqli;
               $this->success        = true;
          }
 
          //IF A PAGE DOESN'T FUNCTION WITHOUT THE DATABASE --AND-- THE CONNECTION FAILED, DISPLAY THE ERROR AND STOP THE SCRIPT
          if($endProgram && !$this->success) {
               print $this->errorText;
               exit;
          }

     }
}
?>

Final Code – Connection Script

<?php
class connect {
     //DECLARE PROPERTIES
     public $success        = false;
     public $errorText      = '';
     public $databaseObject = '';
 
     //CONSTRUCTOR
     public function __construct($endProgram=false) {
          //INITIALIZE VARIABLES
          $host     = 'yourhostname.com';
          $database = 'your_database_name';
          $username = 'your_username';
          $password = 'your_password';
 
          //IF THE DATABASE CONNECTION FAILS, FLAG ERROR
          $mysqli = new mysqli($host, $username, $password, $database);
          if($mysqli->connect_errno) {
               $this->errorText = 'There was a problem connecting to the database that this portion of the website requires to display properly.';
          } else {
               $this->databaseObject = $mysqli;
               $this->success        = true;
          }
 
          //IF A PAGE DOESN'T FUNCTION WITHOUT THE DATABASE --AND-- THE CONNECTION FAILED, DISPLAY THE ERROR AND STOP THE SCRIPT
          if($endProgram && !$this->success) {
               print $this->errorText;
               exit;
          }
     }
}
?>

Using the Connection Script

As before, the connection script can be imported with the require() statement. This time, however, we need to create an instance of a class and grab the database object.

<?php
//CONNECT WITH DATABASE
require "{$_SERVER['DOCUMENT_ROOT']}/../database_connection.php";
$connect = new connect();
$mysqli  = $connect->databaseObject;
?>

For those occasions where the database connection fails, we can avoid those unnecessary database interactions. It doesn't do any good to query a database that isn't available. That's where the $success flag comes in handy.

<?php
//IF THE DATABASE CONNECTION WAS SUCCESSFUL
if($connect->success) {
     //<-- run database queries here } ?>

The flag can also be used for displaying the error message where necessary.

<?php
//IF THE DATABASE CONNECTION FAILED
if(!$connect->success) {
     print $connect->errorText;
}
?>

Conclusion

The new database connection script is still easy to maintain. Since its being imported, like in last week's post, changing the login credentials is quick and painless. Unlike last week, this connection script is better for the visitors. Instead of preventing the entire page from displaying, we can target specific sections for being unavailable.

Related Posts

0 Comments

There are currently no comments.

Leave a Comment