I am trying to understand how error handling in prepared statements in procedural PHP style should work.
According to the documentation, mysqli_prepare
and mysqli_stmt_execute
output the boolean value FALSE
on failure. Great, so if I run the following code I should be able to know when something doesn't work:
if ($my_query= mysqli_prepare($my_conn, "SELECT * FROM my_table")){
if (mysqli_stmt_execute($my_query)){
// DO WHATEVER I NEED TO DO
} else {
// HANDLE ERROR
}
} else {
// HANDLE ERROR
}
The problem is that mysqli_prepare
and mysqli_stmt_execute
do NOT always output False
on failure, they raise an exception. For instance, if my SQL syntax was not right (see following example) I would get a mysqli_sql_exception
.
if ($my_query= mysqli_prepare($my_conn, "SELECTTTT * FROM my_table")){
if (mysqli_stmt_execute($my_query)){
// DO WHATEVER I NEED TO DO
} else {
// HANDLE ERROR
}
} else {
// HANDLE ERROR
}
This calls for a try-catch statement, but then...are the if
even necessary?
My question here is: What's considered a failure in the execution? (no exception rised but those methods return a False value) Is it really necessary to use if
statements if I use a try-catch
block? Because I feel that a try-catch
block would be enough, but the PHP documentation examples (for instance, the mysqli_stmt_fetch examples) only use if
s clauses for dealing with errors.
I would like to hear how you handle failure on this cases. In addition, if you know of any good tutorial regarding this matter, I would appreciate it if you could send me the link. Most tutorials I've seen do not care about error handling.
ANSWER:
If you run the code I provided you might not be able to reproduce my error. The problem was that, after connecting to the database, I had the following line of code:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This turned my warnings into errors, that would throw an exception. Without it, the if
statements DO make sense. The answer is in the comments of this post.