gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:10:13 24 4
gpt4 key购买 nike

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

此代码有效

$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]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (forum.posts, CONSTRAINT posts_ibfk_1 FOREIGN KEY (thread_id) REFERENCES threads (thread_id) ON DELETE CASCADE ON UPDATE CASCADE)

我是 PHP 的新手,所以它可能很简单,我们将不胜感激。

最佳答案

你可以这样做,在插入数据之前设置 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");

关于php - 当外键约束设置为级联时,bindParam 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40315970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com