How to report errors in mysqli
TL;DR
Add the following line before mysqli_connect() (or new mysqli()):
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
then get rid of every manual mysqli error reporting code in your scripts.
Introduction
Reporting errors is the most essential thing in programming. A programmer is effectively deaf-blind if they cannot see errors occurred during the script execution. So it is very important to configure error reporting for your code properly, including database interactions.
By default, when you are running mysqli_query() or - preferably - prepare()/bind()/execute(), mysqli will just silently return false if a query fails, telling you nothing of the reason.
You'll notice the error only when the following command, when trying to use the query result, will raise an error, such as
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
Unfortunately, this error message tells you nothing of the actual problem. It just bluntly says that your query failed, and nothing else.
It happens because by default mysqli is configured to remain silent if a query returned an error. So you can tell that's an extremely inconvenient behavior.
Luckily, mysqli can be configured to throw a PHP exception in case of a mysql error. It means that a PHP error will be thrown automatically every time a query returns an error, without any effort on your part!
Let's see a small demonstration:
// first of all set PHP error reporting in general
// in order to be sure we will see every error occurred in the script
ini_set('display_errors',1);
error_reporting(E_ALL);
/*** THIS! ***/
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
/*** ^^^^^ ***/
$db = $mysqli = new mysqli($host, $user, $pass, $database);
$res = $db->query("apparently not a valid SQL statement");
$res->fetch_assoc();
And run your script again. Whoa! An error appears in a puff of smoke, explaining what was the problem:
Fatal error: Uncaught exception 'mysqli_sql_exception'
with message 'You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
'apparently not valid SQL string' at line 1' in /home/www/test.php:16
Stack trace:
#0 /home/www/init.php(16): mysqli->query('apparently not ...')
#1 /home/www/test.php(2): include('/home/www/...')
#2 {main}
thrown in /home/www/init.php on line 16
As you can see, this is quite a detailed information, including the erroneous part of the query, and even a stack trace that helps you to find a particular function that called the erroneous query.
So again: just make sure that you always have this magic line before mysqli_connect() in all your scripts:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
What to do with the error message you get?
It should be a knee-jerk reflex to copy and paste the error message in Google search. It will lead you to several Stack Overflow questions related to this particular problem with many answers with solutions.
However, there is another possibility. You can try to actually read the error message you get. Usually, the error message explains it pretty straightforward, what is the error. However, some errors could be cryptic. You have to understand some considerations used in Mysql error messages:
- in case of a syntax error, the cited query part begins right after the error.
- it means that, therefore, if the error is at the very end of the query, the cited query part would be an empty string. Most likely it happens when you add a variable directly to the query and this variable happen to be empty (yet another reason to use prepared statements as they will make such errors just impossible to appear.
Related articles:
- Mysqli tutorial (how to use it properly)
- How to connect properly using mysqli
- Why mysqli prepared statemens are so hard to use?
- Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
- How to check whether a value exists in a database using mysqli prepared statements
- Mysqli helper function
- Authenticating a user using mysqli and password_verify()
- How to get the number rows that have been inserted, changed or skipped
- Mysqli's features you probably would like to know about
- Mysqli examples
- How to run INSERT query using Mysqli
- How to use mysqli properly
Comments:
bind_param() seems not to throw an exception, only errors. what do you advice us to do in this case?
Reply:
Hello Daniel!
That's an interesting question. The simplest solution would be to upgrade the PHP version. Starting from 8.0 bind_param is throwing exceptions all right.
For the older versions, it depends on what you need the exception for. Normally, there should be no difference: a Warning as in error all the same, it will be reported and the next call to execute will halt the code execution.
But if you really need and exception, you can add a simple error handler to your code that would convert all errors to excepions, like
See more at https://phpdelusions.net/articles/error_reporting
Hope some of these suggestions will help. If not, then please let me know.
a bit misleading if all you have to do is call mysqli_error() and mysqli_errno() no need to reconfigure anything.
Reply:
Hello Chris!
There are two problems with this mindset.
First, the logic is somewhat inverted here: as long as you have to run only one SQL query, there is not much difference. But even with a dozen, not to mention hundreds of SQL queries, this "call mysqli_error() and mysqli_errno()" after every query becomes "a bit misleading". Now compare it with just "reconfiguring" a single line of code.
Second, the question is, what you're going to do with all these mysqli_error() and mysqli_errno() calls. Are you sure you are going to use them properly? And what if some day you will decide to change that behavior? For example, now you want to die() with the error message but eventually you will learn that it's just gross and it needs to be changed. So, which approach will make it simpler: when you have just a single place where error reporting is configured, or when you have dozens to hundreds places where you need to rewrite the code?