dscpg80066 2017-06-01 10:59
浏览 33
已采纳

删除记录,如果它存在于php / PDO中[重复]

This question already has an answer here:

I have some code that deletes a record from a MySQL database, but I get the success message even if the record does not exist. I have searched for ways of producing a message if the record does not exist but cannot find one that works with my code.

My code is:

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.';
?>

Note to Fred-ii- The answer you referred to is correct, but the terminology in the question I asked was different. I asked how to ensure the RECORD I was deleting existed. I did not ask how to check if a row exists, and would never have thought to search for anything about an existing ROW when I was looking for an existing RECORD. To some experts like yourself a row may be the same as a record, but I and possibly other less enlightened people like me have never heard a record called a row. Best wishes, Tog

</div>
  • 写回答

1条回答 默认 最新

  • dsgk0386 2017-06-01 11:05
    关注

    Use rowCount(); inside try to check number of affected rows by your sql statement

    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();
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题