繁体   English   中英

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

[英]bindParam doesn't work when foreign key constraint set to cascade

我正在为一个任务创建一个论坛站点,代码工作正常,直到我改变了两件事:我将数据库约束更改为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 )REFERENCES threadsthread_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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM