[ Team LiB ] Previous Section Next Section

Finding Out About Errors

So far, we have tested the return values of the MySQL functions that we have used and called die() to end script execution if a problem occurs. You might, however, want to print more informative error messages to the browser to aid debugging. MySQL sets an error number and an error string whenever an operation fails. You can access the error number with mysql_errno() and the error string with mysql_error(). Listing 13.1 brings our previous examples together into a simple script that connects to the server and selects a database. We use mysql_error() to make our error messages more useful. On line 14 we connect to the database. If this is successful, we then select a database on line 19 before closing the connection on line 22. Notice that we suppress any warnings that might be generated by mysql_connect() and mysql_select_db() using the at character (@).

Listing 13.1 Opening a Connection and Selecting a Database
 1: !DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 13.1 Opening a Connection to a Database</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $user = "p24_user";
12: $pass = "cwaffie";
13: $db = "p24";
14: $link = @mysql_connect( "localhost", $user, $pass );
15: if ( ! $link ) {
16:   die( "Couldn't connect to MySQL: ".mysql_error() );
17: }
18: print "<h2>Successfully connected to server</h2>\n\n";
19: @mysql_select_db( $db )
20:   or die ( "Couldn't open $db: ".mysql_error() );
21: print "Successfully selected database \"$db\"<br />\n";
22: mysql_close( $link );
23: ?>
24: </div>
25: </body>
26: </html>

If we change the value of the $db variable in line 13 to "unauthorized", we will be attempting to open a nonexistent database. The output of our die() function call therefore looks something like the following:



Couldn't open unauthorized: Access denied for user:'p24_user@localhost' to database
graphics/ccc.gif 'unauthorized'


    [ Team LiB ] Previous Section Next Section