2017-06-01 43 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

相關問題