我正在尝试调用函数来更新我的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子句中找到数字,我怎样才能正确返回失败?
答案 0 :(得分:2)
execute()
完成后,检查$stmt->affected_rows
是否大于零:
if(!($stmt->execute())){
return "execute failed: [" . $db->errno . "]" . $db->error;
}
if(!$stmt->affected_rows) {
return "no rows updated";
}