当外键约束设置为级联时,bindParam不起作用

时间:2016-10-29 04:15:47

标签: php mysql pdo cascade bindparam

我正在创建一个分配论坛网站,代码工作正常,直到我更改了两件事:我将数据库约束更改为CASCADE(需要像网站其余部分那样)并且我更改了查询功能准备,绑定和执行安全性。

此代码有效

$insert_post_query =
"INSERT INTO posts (
    thread_id, user_id, username, post_content, post_date
)
VALUES (
    '$topic_id', '$user_id', '$username', '$post_content', '$post_date'
)";
$post_result = $db->query($insert_post_query);

此代码不起作用

$insert_post_query =
"INSERT INTO posts (
    thread_id, user_id, username, post_content, post_date
)
VALUES (
    '?', '?', '?', '?', '?'
)";
try{
$post_result = $db->prepare($insert_post_query);
$post_result->bindParam(1,$topic_id,PDO::PARAM_INT);
$post_result->bindParam(2,$user_id,PDO::PARAM_INT);
$post_result->bindParam(3,$username,PDO::PARAM_STR);
$post_result->bindParam(4,$post_content,PDO::PARAM_STR);
$post_result->bindParam(5,$post_date,PDO::PARAM_STR);
$post_result->execute();

}catch(Exception $e){
    echo "Unable to add the post<br>$e";
    exit;
}

这是错误

  

PDOException:SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(forumposts,CONSTRAINT posts_ibfk_1 FOREIGN KEY( thread_id)参考threadsthread_id)更新CASCADE上的DELETE CASCADE)

我对PHP很新,所以它可能很简单,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

你可以这样做,在插入数据集foreign_key_checks = 0之前再次激活它,使用相同的查询行,值为1。

SET foreign_key_checks = 0;
SET foreign_key_checks = 1;

$insert_post_query =
"INSERT INTO posts (
    thread_id, user_id, username, post_content, post_date
)
VALUES (
    '?', '?', '?', '?', '?'
)";
try{
$post_result = $db->prepare("SET foreign_key_checks = 0");
$post_result = $db->prepare($insert_post_query);
$post_result->bindParam(1,$topic_id,PDO::PARAM_INT);
$post_result->bindParam(2,$user_id,PDO::PARAM_INT);
$post_result->bindParam(3,$username,PDO::PARAM_STR);
$post_result->bindParam(4,$post_content,PDO::PARAM_STR);
$post_result->bindParam(5,$post_date,PDO::PARAM_STR);
$post_result->execute();
}catch(Exception $e){
    echo "Unable to add the post<br>$e";
    exit;
}
$post_result = $db->prepare("SET foreign_key_checks = 1");
相关问题