2017-06-01 40 views
0

我有一些代码从MySQL数据库中删除记录,但即使记录不存在,我也会收到成功消息。如果记录不存在但找不到可与我的代码一起使用的消息,我已经搜索了生成消息的方法。删除记录,如果它存在于php/PDO

我的代码是:

try { 
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); 
    /*** echo a message saying we have connected ***/ 
    //echo 'Connected to database<br />'; 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $sql = "DELETE FROM ukgh WHERE telephone = :telephone"; 
    $stmt = $dbh->prepare($sql); 
    $stmt->bindParam(':telephone', $telephone, PDO::PARAM_STR); 
    $stmt->execute(); 

    /*** close the database connection ***/ 
    $dbh = null; 
} 
catch(PDOException $e) { 
    echo $e->getMessage(); 
} 
// once processing is complete 
// show success message 
echo 'Success - The record for ' . $telephone . ' has been deleted.'; 
?> 

注弗雷德-II-你提到的答案是正确的,但在我问的问题的术语是不同的。我问如何确保我删除的RECORD存在。我没有问过如何检查一行是否存在,并且当我正在查找现有的RECORD时,从来没有想过要搜索任何有关现有ROW的内容。对于像你这样的一些专家来说,一行可能与一条记录相同,但是我和其他像我这样不那么开明的人从来没有听说过一行记录。最良好的祝愿,火车

+0

为什么它不是成功,检查受影响的行数,如果记录不存在?目标达成了,在这两种情况下,记录不再存在 – Jens

+1

您必须检查受影响的行:http://php.net/manual/de/pdostatement.rowcount.php – Jens

+0

您收到消息,因为它位于尝试,将其放入TRY。 – RiggsFolly

回答

3

使用rowCount();内尝试通过SQL语句

try { 
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); 
    /*  * * echo a message saying we have connected ** */ 
//echo 'Connected to database<br />'; 
    $sql = "DELETE FROM ukgh WHERE telephone = :telephone"; 
    $stmt = $dbh->prepare($sql); 
    $stmt->bindParam(':telephone', $telephone, PDO::PARAM_STR); 
    $stmt->execute(); 
    $count = $stmt->rowCount();// check affected rows using rowCount 
    if ($count > 0) { 
     echo 'Success - The record for ' . $telephone . ' has been deleted.'; 
    } else { 
     echo "Your error message"; 
    } 
} catch (PDOException $e) { 
    echo $e->getMessage(); 
} 

http://php.net/manual/en/pdostatement.rowcount.php

相关问题