I'm creating a forum site for an assignment and the code worked fine until I changed two things: I changed my database constraints to CASCADE (needs to be like that for the rest of the site) and I changed the query function to prepare, bind and execute for security.
This code works
$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);
This code doesn't work
$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;
}
This is the error
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
forum
.posts
, CONSTRAINTposts_ibfk_1
FOREIGN KEY (thread_id
) REFERENCESthreads
(thread_id
) ON DELETE CASCADE ON UPDATE CASCADE)
I'm fairly new to PHP so it could be something simple, and any help would be appreciated.