The first thing you need to do is connect to the database and check to make sure there's a connection. Including the file that you set up to store your connection information allows you to use the variables instead of hardcoded values when you call the mysql_connect function, as shown in Example 9-4.
Example 9-4. Including the connection values and calling mysql_connect
$connection = mysql_connect($db_host, $db_username, $db_password);
die ("Could not connect to the database: <br />". mysql_error());
The mysql_connect function takes the database host, username, and password as parameters. If the connection is successful, a link to a database is returned. FALSE is returned if a connection can't be made. Check the return value from the function to make sure there's a connection. If there's a problem, such as an incorrect password, print out a polite warning and the reason for the error using mysql_error.
Instead of simply echoing an error message, use the die function to display the error, and then stop the program, Not being able to access the database makes most database-driven pages fairly useless and prevents the user from seeing numerous errors.
Notice that we didn't specify the database name yet.
Troubleshooting connection errors
One error you may get is:
Fatal error: Call to undefined function mysql_connect() in C:Program FilesApache
GroupApache2htdocstest.php on line 4
This occurs because PHP 5.1.2 for Windows was downloaded, and MySQL support was not included by default. To fix this error, copy the php_mysql.dll file from the ext/ directory of the PHP zip file to C:php, and then edit lines 461 and 589 of C: WINDOWSphp.ini. This will change the extension to include the directory to C:/php and uncommenting the MySQL extension line, respectively.
You'll need to restart Apache, and then MySQL support will be enabled.
Please check back next week for the continuation of this article.