首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PDO-删除不存在行的异常

问PDO-删除不存在行的异常
EN

Stack Overflow用户
提问于 2015-06-15 15:59:09
回答 2查看 855关注 0票数 0

在我的桌子上

代码语言:javascript
复制
id |name
1  | one

然后

代码语言:javascript
复制
$id = '2';
$sql=$this-con->query("delete from  aTable WHERE id = '".$id."' " );

行将执行以下操作

代码语言:javascript
复制
/* Affected rows: 0  Found rows: 0  Warnings: 0  Duration for 1 query: 0.000 sec. */

即使表中没有这样的id 2。

我怎么能用PHP或者SQL来阻止这种情况呢?因为在我的PHP中,我需要告诉用户没有这样的行,但是如何在不首先检查自定义code.Because的情况下捕获丢失的行:

代码语言:javascript
复制
 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
      }

你明白我的意思吗?或者没有这样的方式,除非先进行自定义检查?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-15 16:12:05

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

试试这个:

$nrows =$this-con->查询(“从aTable中删除id =‘’.$id.‘”)->fetchColumn();

票数 2
EN

Stack Overflow用户

发布于 2015-06-15 16:30:06

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

对于PDO,您可以使用准备语句,然后获得如下所示的rowCount:

代码语言:javascript
复制
$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():

代码语言:javascript
复制
$result = mysql_query("delete from  aTable WHERE id = '".$id."' ");
if(mysql_affected_rows()) {
    // record found and deleted
} else {
    // no such record in the database
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30849738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档