Connecting to MySQL

Now that you have the login.php file saved, you can include it in any PHP files that will need to access the database by using the require_once statement. This has been chosen in preference 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. Following example shows the code to use.

<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
?>

This example runs PHP’s mysql_connect function, which requires three parameters, the hostname, username, and password of a MySQL server. Upon success it returns an identifier to the server; otherwise, FALSE is returned. Notice that the second line uses an if statement with the die function, which does what it sounds like and quits from PHP with an error message if $db_server is not TRUE.
 
The die message explains that it was not possible to connect to the MySQL database, and—to help identify why this happened—includes a call to the mysql_error function. This function outputs the error text from the last called MySQL function.
 
The database server pointer $db_server will be used in some of the following examples to identify the MySQL server to be queried. Using identifiers this way, it is possible to connect to and access multiple MySQL servers from a single PHP program.

The die Function

The die function is great for 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 format a message that will be displayed when the program exits normally, such as:

<?php function mysql_fatal_error($msg)
{
	$msg2 - mysql_error();
	echo <<< _END
	We are sorry, but it was not possible to complete
	the requested task. The error message we got was:
	<p>$msg: $msg2</p>
	Please click the back button on your browser
	and try again. If you are still having problems,
	please <a href="mailto:admin@server.com">email
	our administrator</a>. Thank you.
	_END;
}
?>