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

≡放荡痞女 提交于 2020-06-19 04:46:08

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/62216426/should-i-manually-check-for-errors-when-calling-mysqli-stmt-prepare

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!