Maintain Your Database Login Information with Ease by Externalizing the Connection Script

When working with databases like MySQL, a connection needs to be established before processing any queries. That connection script could be added to the top of every page needing access, but what happens when the database password needs updating. Who wants to update dozens (or thousands) of files? As a solution, let's look at externalizing the code that makes the connection and importing it instead.

First, we'll create the connection script. Note that this example uses MySQLi, but the code could be adapted for PDO_MySQL or the depreciated MySQL format. To make the connection, PHP needs some information about the database.

<?php
//INITIALIZE VARIABLES
$host = 'yourhostname.com';
$database = 'your_database_name';
$username = 'your_username';
$password = 'your_password';
?>

Of course, the information needs to be changed to work with your database. We can now execute the mysqli() function. If the connection fails, we'll display an error and stop the script going further.

<?php
//INITIALIZE VARIABLES
$host = 'yourhostname.com';
$database = 'your_database_name';
$username = 'your_username';
$password = 'your_password';
$password = 'your_password';
 
//IF WE'RE UNABLE TO CONNECT WITH THE DATABASE, DISPLAY ERROR AND STOP THE SCRIPT
$mysqli = new mysqli($host, $username, $password, $database);
if($mysqli->connect_errno) {
     print '<p>There was a problem connecting to the database.</p>';
     exit();
}

?>

The completed connection script is saved to a file we'll call "database_connection.php". The file should then be uploaded to a place on the web server which isn't accessible via the URL. That way if the server is ever misconfigured, the database credentials won't be exposed and placed into the wrong hands. Let's store the script just outside of the website's root directory.

The connection script can now be imported where needed with the require() statement.

<?php
//CONNECT WITH DATABASE
require "{$_SERVER['DOCUMENT_ROOT']}/../database_connection.php";
?>

Conclusion

Having the database connection script in its own file makes changing the login credentials a very simple task. It may even be simple enough that we'll actually change the login every once in a while.

0 Comments

There are currently no comments.

Leave a Comment


Warning: Undefined variable $user_ID in /home/cyberscorp/webdev.cyberscorpion.com/wp-content/themes/scorpbytes/comments.php on line 72