0

我正在尝试调用一个函数来更新我的 mysqli 数据库,并在发生错误时报告。到目前为止,我的测试文件中有这个:

<?php

$success = test("cat",17);
echo $success;
echo "<br />";


function test($name, $number){
    $db = new mysqli("localhost","root","","test");
    if($db->connect_errno){
        return "Failed to connect to MYSQL Database: [" . $db->connect_errorno . "]" . $db->connect_error;
    }
    if(!($stmt = $db->prepare("UPDATE `test` SET `name` = ? WHERE `number` = ?"))){
        return "prepare failed: [" . $db->errno . "]" . $db->error;
    }
    if(!($stmt->bind_param('si', $name, $number))){
        return "bind failed: [" . $db->errno . "]" . $db->error;
    }
    if(!($stmt->execute())){
        return "execute failed: [" . $db->errno . "]" . $db->error;
    }
    $stmt->close();
    return "Successfully updated database!";
}

?>

并且通过我在那里的测试 (cat, 17) 它返回成功,即使没有数字为 17 的列,并且我看到数据库中没有任何变化。如果在 WHERE 子句中找不到数字,如何让它正确返回失败?

4

1 回答 1

2

完成execute()后,检查$stmt->affected_rows是否大于零:

if(!($stmt->execute())){
    return "execute failed: [" . $db->errno . "]" . $db->error;
}

if(!$stmt->affected_rows) {
    return "no rows updated";
}
于 2013-05-07T17:31:20.920 回答