删除记录并计算行以检查结果

时间:2014-03-17 16:56:51

标签: php mysql sql

所以我尝试使用php和sql从表中删除记录,并检查是否已使用if语句中的rowcount()函数删除它。

我在两个方面都遇到了问题......

<?php

        echo $_GET['id'];

        if (isset($_GET['id'])) {
            $trainingID = $_GET['id'];
        }
        else {
            die('There was a problem with the ID given.');
        }

      // include the connection file
      require_once('./includes/connection.inc.php');
      $conn = dbConnect();
      // prepare SQL statement
      $sql = 'DELETE FROM  `trainingCourses` WHERE  `trainingID` =  "$trainingID"';
      $stmt = $conn->prepare($sql);
      try {
          $stmt->execute();
          echo "deleted";
          echo $stmt->rowcount();
          //check number of rows affected by previous insert
          if ($stmt->rowCount() == 1) {
              $success = "$trainingID has been removed from the database.";
          }
      }
       catch(PDOException $e){
           echo $e;
           echo 'Sorry, there was a problem with the database.';
      }

    ?>

我目前在我的代码中从我的回声中输出了3个东西,首先我得到了T0001,这是我要从另一个页面删除的记录的主键。其次我得到“删除”,这是来自我的'try'语句中的回声,但记录实际上并没有从数据库中删除。这是从输出0的rowcount()函数备份的。

我似乎无法让这个工作,我确信它应该是简单的,我只是忽略了!

如果try方法中的“if”语句失败,那么try方法是否默认为catch?我还不确定删除行时应该从rowcount()输出什么?

您提供的任何帮助都会非常有用!谢谢!

1 个答案:

答案 0 :(得分:1)

回应这一行

$sql = 'DELETE FROM  `trainingCourses` WHERE  `trainingID` =  "$trainingID"';

会将$trainingID视为字符串,而不是变量。

$sql = "DELETE FROM  `trainingCourses` WHERE  `trainingID` =  '$trainingID'";

将完成的工作不安全(sql注入)。您应该使用PDO来绑定像这样的变量

$sth = $dbh->prepare("DELETE FROM  `trainingCourses` WHERE  `trainingID` =  :id");
$sth->bindParam(":id",$trainingID);
$sth->execute();