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

时间:2015-02-19 05:57:31

标签: php mysql pdo prepared-statement

为什么我的代码无效。帮助,我没有看到任何错误。如果我使用user_id = $ current_user而不是user_id =:current_id,它可以工作。但我需要为安全起见做准备。请帮助。

<?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 个答案:

答案 0 :(得分:1)

@conan,使用我提到的以下代码&amp;您需要使用此代码检查以下几点。

1)打印$ current_user id以确保ID是否正确显示,如果post包含用户ID,则只有查询正在执行时,我已经设置了条件。

2)我已经设置了异常,因此您可以通过异常消息检查错误。

<?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 :(得分:1)

$ current_user是整数还是字符串。如果字符串尝试PDO :: PARAM_STR而不是PDO :: PARAM_INT

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

如果仍然无效,请尝试此

//$stmt->bindParam(":current_id",$current_user,PDO::PARAM_STR);
$stmt->execute(array(:current_id"=>$current_user));