用于删除不存在的行的 PDO 例外


PDO-exception for deleting not existing row

在我的表格中

id |name
1  | one

然后

$id = '2';
$sql=$this-con->query("delete from  aTable WHERE id = '".$id."' " );

该行将执行

/* Affected rows: 0  Found rows: 0  Warnings: 0  Duration for 1 query: 0.000 sec. */

甚至他们的 id 也没有这样的 id 2在表中.

我怎么能设法用PHPSQL来防止这种情况.因为在我的 PHP 中,我需要告诉用户没有这样的行,但如何捕获丢失的行而不首先通过自定义代码检查它。因为:

 if($sql){
// Tell user the row is deleted, but (in fact there is no such row with the id in the column)
        }
     else{
      // there must be exception goes here
      }

你明白我的意思吗? 或者没有先进行自定义检查就没有这种方法?

PDO::exec()返回您发出的 SQL 语句修改或删除的行数。如果没有行受到影响,则PDO::exec()返回 0。

试试这个:

$nrows = $this-con->query("delete from aTable WHERE id = "'".$id.")->fetchColumn();

你在PHP中使用PDO还是纯MySQL函数?

使用 PDO,您可以使用预准备语句,然后像这样获取 rowCount:

$st = $conn->prepare("delete from  aTable WHERE id = '".$id."' " );
$st->execute();
if($st->rowCount()) {
    // return the number of affected rows: Record deleted
} else {
    // no such record in the database
}

如果您使用的是纯MySQL函数(并且您真的不应该使用它们),请使用mysql_affected_rows():

$result = mysql_query("delete from  aTable WHERE id = '".$id."' ");
if(mysql_affected_rows()) {
    // record found and deleted
} else {
    // no such record in the database
}