2015-06-15 29 views
0

在我的桌子PDO的异常删除不存在

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 2在桌子 。

我该如何设法防止这种情况,PHPSQL。 因为在我的PHP我需要告诉用户,有没有这样的行,但如何抓住失踪行,不检查其第一槽定制code.Because:

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 
     } 

你明白我的意思吗?或者没有这种方式没有先定制检查?

+0

你应该开始使用预处理语句 – DarkBee

+0

@DarkBee,是的,我很使用它,这只是我创建来解释我的问题的简短快速片段。 –

回答

2

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

试试这个:

$ NROWS = $这个-CON组>查询(“”从aTable WHERE ID = 删除 “” $ ID。“ ““) - > fetchColumn();

+0

是的,'PDO :: exec()'完成了这项工作,谢谢! –

2

您是否使用PDO或PHP

纯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 
} 
+0

你是什么意思?如果你使用纯粹的MySQL函数(你真的不应该使用它们)? –

+0

@NatNaydenova,如果您要使用准备好的语句,那么您应该使用$ id值的参数来防止SQL注入。 –

+0

@MarkLeiber你绝对正确,但我决定不在问题范围内 –