外键约束失败错误

时间:2017-06-26 08:55:29

标签: php mysql

尝试更新连接表时出现以下错误:

Notice: Undefined variable: id
Notice: Undefined variable: course_id

Cannot add or update a child row: a foreign key constraint fails (`school-project`.`students_courses`, CONSTRAINT `fk_courses` FOREIGN KEY (`course_id`) REFERENCES `courses` (`id`) ON DELETE CASCADE)0 Row inserted.

3个表是:

#   Name    Type    Collation   Attributes  Null    Default Comments    Extra
1   id Primary Index    int(11)         No  None        AUTO_INCREMENT
2   student_id Index    int(11)         No  None        
3   course_id Index int(11)         Yes NULL    


#   Name    Type    Collation   Attributes  Null    Default Comments    Extra
1   idPrimaryIndex  int(11)         No  None        AUTO_INCREMENT
2   name    varchar(255)    latin1_swedish_ci       No  None        
3   phone   varchar(20) latin1_swedish_ci       No  None        
4   email   text    latin1_swedish_ci       No  None        
5   image   text    latin1_swedish_ci       No  None    

#   Name    Type    Collation   Attributes  Null    Default Comments    Extra

1   idPrimaryIndex  int(11)         No  None        AUTO_INCREMENT
2   nameIndex   varchar(20) latin1_swedish_ci       No  None        
3   descr   text    latin1_swedish_ci       No  None        
4   image   text    latin1_swedish_ci       No  None    

代码:

function joinTable() {
    global $connection;
    $join_table_sql = "INSERT INTO students_courses (student_id, course_id)
VALUES ('$id', '$course_id')";
    if ($connection->query($join_table_sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $join_table_sql . "<br>" . $connection->error;
    }
}
我错过了什么?为什么我会得到那些错误?

1 个答案:

答案 0 :(得分:1)

如何获得$id$course_id

第一个错误出现在PHP Notice中,您也没有在sql中插入空值

*这应该是评论,但我没有声誉...... :(