Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

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 12.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 11 we connect to the database. If this is successful we then select a database on line 15 before closing the connection on line 18.

Listing 12.1 Opening a Connection and Selecting a Database

 1: <html>
 2: <head>
 3: <title>Listing 12.1 Opening a connection and 
 4: selecting a database</title>
 5: </head>
 6: <body>
 7: <?php
 8: $user = "harry";
 9: $pass = "elbomonkey";
10: $db = "sample";
11: $link = mysql_connect( "localhost", $user, $pass );
12: if ( ! $link )
13:   die( "Couldn't connect to MySQL" );
14: print "Successfully connected to server<P>";
15: mysql_select_db( $db ) 
16:   or die ( "Couldn't open $db: ".mysql_error() );
17: print "Successfully selected database \"$db\"<P>";
18: mysql_close( $link );
19: ?>
20: </body>
21: </html>

If we change the value of the $db variable in Line 10 to "notthere", we will be attempting to open a nonexistent database. The output of our die() function call will look something like the following:

Couldn't open sample2: Access denied for user: 'harry@localhost' to database 'notthere'
  • + Share This
  • 🔖 Save To Your Account