如何测试MySQL查询修改数据库表数据是否成功?
我有以下简单的 php 代码片段,它会在调用时从数据库中删除相关文章.结果被传递给一个 javascript 函数,该函数将通过 AJAX 更新页面.如果查询失败,我想返回字符串 false
,如下所示.
I have the following simple php code snippet, which will, when called, delete a relevant article from a database. The result is passed to a javascript function, which will update the page via AJAX. I would like to return the string false
if the query fails, as I've below.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
$delRecord->close();
echo "true";
} else {
echo "false";
}
}
我想知道我遗漏了什么以及检查查询是否成功的正确方法.
I would like to know what I have missed and the correct way to check if a query was successful or not.
你需要使用 mysqli->affected_rows() 用于检查查询是否成功(或者您可以使用 mysqli_stmt->execute() 的结果值.
You need to use mysqli->affected_rows() for checking if the query was successful (or you could use mysqli_stmt->execute()'s result value).
以你的例子为例,除了上面的内容什么都不修改:
Taking your example, and modifying nothing but for the above:
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
if ($delRecord->affected_rows > 0) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
}