检查mysqli查询是否成功的正确方法

010*_*101 5 php database mysqli prepared-statement

我已经阅读了几篇关于这个问题的文章,但是他们都没有帮助我,我有点困惑该做什么.

基本上,我想检查sql查询是否执行没有任何错误.为此,我是否必须使用if下面显示的两个语句?

if($stmt = $mysqli->prepare("INSERT INTO table VALUES (?, ?, ?);"))
{
    $stmt->bind_param("sss", $a, $b, $c);

    if(!$stmt->execute())
    {
        // Do I have to catch the problem here?
    }

    if($stmt->affected_rows === -1){
       // Do I have to catch the problem here?
    }

    $stmt->close();
}
else
{
    // Do I need to catch the problem here?
}
Run Code Online (Sandbox Code Playgroud)

Sve*_*sen 4

prepare()您应该检查、bind_param()和的返回值execute()false如果失败的话他们都会回来。

如果execute()没有返回false,那么INSERT应该已经成功完成,因此affected_rows只有当您想知道有多少行受到影响时,检查才有意义。