The db.php Include File

As discussed in Chapter 14 in Modularizing Code,” include files can be used to provide a single definition for variable values or function declarations used by multiple scripts in an application. In our application, all our scripts need to use the same connection and authentication credentials to communicate with the database. We have previously described the custom clean() and logincheck() functions in Untainting User Data,” in Chapter 14 and Authenticating the User,” earlier in this chapter, and before that we wrote the showerror() function in Handling MySQL Errors” in Chapter 14. Since these functions are used across several PHP scripts, we can place the function definitions in a common include file that is loaded by the scripts that need it. This helps to keep code easy to maintain; any change to data or definitions in an include file is automatically in effect for the scripts that use it.

We can place the function definitions, along with the database connection details, in the file db.php:

<?php // These are the DBMS credentials and the database name $DB_hostname = "localhost"; $DB_username = "fred"; $DB_password = "shhh"; $DB_databasename = "wedding"; // Show an error and stop the script function showerror($connection) { // Was there an error during connection? if(mysqli_connect_errno()) // Yes; display information about the connection error die("Error " . mysqli_connect_errno($connection) . " : " .mysqli_connect_error($connection)); else // No; display ...

Get Learning MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.