Now that you have saved the login.php file, you can include it in any PHP files that will need to access the database by using the require_once statement. This is preferable to an include statement, as it will generate a fatal error if the file is not found—
and believe me, not finding the file containing the login details to your database is a fatal error.
Also, using require_once instead of require means that the file will be read in only when it has not previously been included, which prevents wasteful duplicate disk accesses.
Connecting to a MySQL server with mysqli
<?php
require_once ‘login.php’;
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die(“Fatal Error”);
?>
This example creates a new object called $conn by calling a new instance of the mysqli method, passing all the values retrieved from the login.php file. We achieve error checking by referencing the $conn->connect_error property.
The -> operator indicates that the item on the right is a property or method of the object on the left. In this case, if connect_error has a value, there was an error, so we call the die function to terminate the program.
The $conn object is used in the following examples to access the MySQL database.
The die function is great when you are developing PHP code, but
of course you will want more user-friendly error messages on a
production server. In this case, you won’t abort your PHP program,
but will format a message that will be displayed when the program
exits normally—perhaps something like this:
function mysql_fatal_error()
{
echo <<< _END
We are sorry, but it was not possible to complete
the requested task. The error message we got was:
Fatal Error
Please click the back button on your browser
and try again. If you are still having problems,
please email our administrator. Thank you.
_END;
}
You should also never be tempted to output the contents of any
error message received from MySQL. Rather than helping your
users, you could give away sensitive information to hackers such as
login details. Instead, just guide the user with information on how
to overcome their difficulty based on what the error message
reports to your code.