5.5. Handling MySQL Errors

You use the mysqli functions of the PHP language, such as mysqli_connect and mysqli_query, to interact with the MySQL database. Things will sometimes go wrong when you use the statements. You may make an error in your typing, such as mistyping a database name. Sometimes, problems arise that you can't avoid, such as the database or the network being down. You need to include code in your script that handles error situations.

You can read about PHP error handling in Book II, Chapter 1. That chapter describes the types of errors that PHP displays and how to turn them on and off. As discussed in Book II, you usually want to make your error handling more descriptive to assist with troubleshooting problems during development, but you don't want the extra information displayed to the public.

For instance, suppose that you're using an account called root to access your database and you make a typo, as in the following statements:

$host = "localhost";
$user = "rot";
$password = "";
$cxn = mysqli_connect($host,$user,$password)

Because you type "rot" rather than "root", you see a warning message similar to this one:

Warning: Access denied for user: 'rot@localhost' (Using password: NO) ...

The preceding error message contains the information that you need to figure out the problem — it shows your account name that includes the typo. However, after your script is running and customers are using it, you don't want your users to see a technical error message that shows ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.