外键MySQL错误与帖子

时间:2016-12-07 10:48:11

标签: php mysql

我的MySQL代码尝试将帖子提交到论坛时出错了。

错误是:

    Cannot add or update a child row: a foreign key constraint fails(`[My Database Name]`.`posts`, CONSTRAINT `posts_ibfk_2` FOREIGN KEY (`post_by`) REFERENCES `users` (`id`) ON UPDATE CASCADE)

代码是:

            $username = $_SESSION['username'];
            $subid = mysqli_insert_id($con);
            $usablesubid = mysqli_real_escape_string($con,$subid);
            $postcontent = mysqli_real_escape_string($con,$_POST['post_content']);
            $usableusername = mysqli_real_escape_string($con,$username);
            $sql = "INSERT INTO `posts`(post_id, post_content, post_date, post_sub, post_by)VALUES(NULL, '$postcontent', NOW(), '$usablesubid', '$usableusername')";
            $result = mysqli_query($con,$sql);                 
            if(!$result)
            {
                echo 'An error occured while inserting your post. Please try again later.' . mysqli_error($con);

2 个答案:

答案 0 :(得分:0)

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails这意味着,您尝试在帖子表格中添加一行用户中没有匹配的行 post_by 表。

有关详细信息check here

答案 1 :(得分:0)

无法添加或更新子行:外键约束失败

错误是不言自明的。这是因为您的代码违反了外键的父子关系。

前:

table1: tbl_emp
     id    emp_name
     1     Ajay

table2: here emp_id is a reference to id of tbl_emp
     id    emp_id    emp_name
     1     2         Ajay

在这种情况下,您无法添加上述记录,因为父表中 id-> 2 没有父条目