在使用预准备语句删除之前检查值是否存在
问题描述:
我想在电影不存在时收到通知。这表示从数据库中删除电影的脚本。 这是什么,我现在有一个部分:在使用预准备语句删除之前检查值是否存在
$title = $_POST["title"];
$delMovie = mysqli_prepare($link, "DELETE FROM movie WHERE title=?");
mysqli_stmt_bind_param($delMovie, "s", $title);
if (mysqli_stmt_execute($delMovie)) {
echo("Movie \"" . $title . "\" successfully deleted: ");
echo(mysqli_stmt_affected_rows($delMovie) . " rows affected");
} else {
echo("Error (" . mysqli_stmt_errno($delMovie) . "): ");
echo(mysqli_stmt_error($delMovie));
}
mysqli_stmt_free_result($delMovie);
mysqli_stmt_close($delMovie);
mysqli_close($link);
当影片不存在,但它仍然会返回:
Film "Movie1" successfully deleted: 0 rows affected
正如你所看到的,它不存在,但仍返回“成功”。我怎样才能改变这种显示:
Error: Movie does not exists in database
答
如何如下:
if (mysqli_stmt_affected_rows($delMovie) == 0) then
echo "Error: Movie does not exists in database";
只是因为MySQL返回0,并不意味着你必须拿出结果,仿佛这是不止一个。
=============================================
你是唯一的其他选择是
1) Do a select statement to check for existence
2) If not exists
a) Show error
b) Delete
- If error deleting, show error
- Else show success
或
1) Delete
- If 0 rows affected or error, Show error message
- Else show success
我认为第二个路径上的变化使得更清洁的代码。
+0
像魅力一样工作,谢谢:) – Patrick2607 2014-10-07 21:14:22
它成功返回,因为查询没有失败并显示错误。没有受到影响的行。 – 2014-10-07 20:45:58
为什么不只是将'mysqli_stmt_affected_rows($ delMovie)'存储在一个变量中,并且如果== 0回显出不同的消息。只要运行删除查询并且不删除任何行就不会造成伤害。然后你只运行一个查询,反正会更快。 – 2014-10-07 20:47:26
由于后者受到丑陋[竞争条件](http://en.wikipedia.org/)的限制,“删除并查看是否有任何东西”删除方法比“测试和条件删除”方法好得多。 wiki/Race_condition)你的测试可能会失败,但记录稍后会出现。 – tadman 2014-10-07 20:49:51