douweng3564 2015-02-19 05:57
浏览 45
已采纳

我的代码有什么问题,mysql,PDO准备删除语句?

Why my code is not working. Help, I don't see any wrong. If I use user_id=$current_user instead of user_id=:current_id, it works. But I need to prepare for security reason. Help please.

<?php
$hostname = 'localhost';
$username = '**';
$password = '**';
$dbname = '**';
try {
    $db = new PDO("mysql:host=$hostname;dbname=$dbname", "$username" ,"$password" , 
        array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

} catch (PDOException $e) {
    echo" There was an error with the connection";
}

$current_user=$_POST['users_id'];//get user id

include 'db_tag.php';
$stmt=$db->prepare("DELETE FROM object_sign WHERE user_id=:current_id");

$stmt->bindParam(":current_id",$current_user,PDO::PARAM_INT);
$stmt->execute(); 

?>
  • 写回答

2条回答 默认 最新

  • doudao2407 2015-02-19 06:14
    关注

    @conan, Use below code that I have mentioned & you need to check below points with this code.

    1) Print $current_user id to make sure id correctly appeared or not,Also I have put condition if post contain user id then only query being executed.

    2) I have put exception so you can check errors through exception message.

    <?php
    include 'db_tag.php';
    
    $hostname = 'localhost';
    $username = '**';
    $password = '**';
    $dbname = '**';
    
    try {
         $db = new PDO("mysql:host=$hostname;dbname=$dbname", "$username" ,"$password" , 
            array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    
        if(isset($_POST['users_id'])) {
            $current_user=$_POST['users_id'];//get user id
    
            $stmt=$db->prepare("DELETE FROM object_sign WHERE user_id=:user_id");
    
            $stmt->bindParam(":user_id",$current_user);
            $stmt->execute(); 
        } 
    } catch(PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化