The goal of this script is simply to connect to MySQL, running on your machine (localhost).
Open a new file in your text editor and start a PHP block:
<?
Create a variable to hold the result of the mysql_connect() function:
$connection = mysql_connect("localhost", "spike", "9sj7En4")
| Note |
The mysql_connect() function requires a host name, username, and password (in that order). |
Add a die() function to the mysql_connect() line to cause the script to end and a message to be displayed if the connection fails. Within the die() function, use the mysql_error() function. The message that is printed upon error is the exact error as sent by MySQL. The new line should read as follows:
$connection = mysql_connect("localhost", "spike", "9sj7En4")
or die(mysql_error());
Test the value of $connection. If it's true, the connection to MySQL was made, and a variable is created to hold a message:
if ($connection) {
$msg = "success!";
}
| Note |
If a connection cannot be made, the script will end with the die() function. |
Close your PHP block, and then add HTML:
?> <HTML> <HEAD> <TITLE>MySQL Connection</TITLE> </HEAD> <BODY>
Print the message string:
<? echo "$msg"; ?>
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name db_connect.php, and place this file in the document root of your web server.
Open your web browser and type http://127.0.0.1/db_connect.php.
If you entered the correct username and password, you should have a successful result.
Anytime you work with databases, you will have errors. It's inevitable. That's why I want to show you some common errors and how to handle them fairly gracefully.
You'll make a modification to the db_connect.php script that causes it to fail on connection, simply by changing the username.
Change the username to buffy (unless buffy is a real user!) so that the connection line reads as follows:
$connection = mysql_connect("localhost", "buffy", "9sj7En4")
or die(mysql_error());
Save the file, and then open your web browser to http://127.0.01/db_connect.php.
That is some kind of nasty response! At least it tells you exactly what is wrong, and several times over: user buffy couldn't connect to MySQL. You can suppress one of the ugly warnings and just go with the message from the die() function by placing a @ before the mysql_connect() function name. Try it.
Add a @ before the mysql_connect() function, keeping the bad username:
$connection =
@mysql_connect("localhost",
"buffy", "9sj7En4")
or die(mysql_error());
Save the file, and then open your web browser to http://127.0.0.1/db_connect.php.
With this change, the warning is suppressed, and only the message from the die() function is displayed. This is a meaningful error message output from the mysql_error() function.
If you can keep nasty errors and warnings to a minimum, it will make the overall user experience much more pleasant if your database decides to render itself unavailable during peak web-surfing hours.