如何检查ID是否为';不存在.


How can I check if the ID doesn't exist..?

我正在为class制作一个游戏,我决定添加一个能够报告评论的评论系统。我创建了一个名为comments的表,并在表中创建了一列report_active。当用户报告注释时,该列中的值将变为1。然后,所有在active_report列中带有1的注释都会列在adminCP中。

有一个名为comments.php的文件,它列出了所有评论,并允许用户添加新的评论。在每条评论旁边,我添加了一个报告按钮,链接到一个名为report_comment.php的文件。我使用这个文件来运行更新查询。

这个文件看起来像这样:

<?php
session_start();
require_once('db_connect.php');
require_once('security.php');
if (isset($_GET['id'])) {
    $report_active = 1;
    $id = $_GET['id'];
    $update = $db->prepare("UPDATE comments set report_active = ? WHERE id = ?");
    $update->bind_param('ii', $report_active, $id);
    if ($update->execute()) {
        $_SESSION['reported'] = 'reported';
        header('Location: comments.php');
        die();
    }
} else {
    header('Location: comments.php');
}
 ?>

会话变量$_SESSION['reported']是我用来确定是否向用户显示一个警告的,上面写着Comment Reported,然后我取消设置会话。

我要问的是,我如何检查作为$_GET请求发送的ID是否确实存在,如果确实存在,则运行通常的$_SESSION['reported'],如果没有,则设置新的会话$_SESSION['errorReport'],然后显示错误警报?

我试过:

然而,if ($update->execute() && $update->num_rows) {没有起作用。

我还有别的办法吗?

您可以像现在一样执行查询,并使用rowCount()affected_rows:检查是否有任何行被修改

if ($update->execute()) {
  if ($update->affected_rows > 0)
  {
    $_SESSION['reported'] = 'reported';
    header('Location: comments.php');
    die();
  }
  else
  {
    // no row was modified / the ID does not exist.
  }
}

编辑:最初的答案适用于PDO,对于mysqli,您需要$update->affected_rows