Skip to content
Advertisement

Should I manually check for errors when calling “mysqli_stmt_prepare”?

I’m using PHP and mysqli prepared statements. Is there a compelling reason to manually check for errors when executing mysqli_stmt_prepare()? To be more specific I am not asking about the final result just the prepare statement line.

$sql = "SELECT * FROM `users`;";
$stmt = mysqli_stmt_init($db);
mysqli_stmt_prepare($stmt, $sql); // How should I check for error in here
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

PHP manual puts this and only this line in an if statement.

$sql = "SELECT * FROM `users`;";
$stmt = mysqli_stmt_init($db);
if (mysqli_stmt_prepare($stmt, 'SELECT * FROM `users`;')) {
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
}

I would like to know how to properly check for errors when using prepared statements in mysqli. Is there a good reason to manually check the return value of that function as it is shown in the manual?

Advertisement

Answer

Is there a good reason to manually check the return value of that function as it is shown in the manual?

Nope, there isn’t.

Mysqli can check for errors automatically, you just have to ask it to do so.
Configure mysqli to throw an exception every time it gets an error, and you won’t have to check any mysqli function for the error manually anymore!

Hence, add the following line before mysqli_connect()

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

and that’s all!

Note that you have to deal with possible errors the right way. You can read about it in my article, PHP error reporting

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement