我有两个提交按钮,它们从两个表单中获取值并将它们插入数据库中。问题是我需要从第一个表(课程)中获取最后插入的id以插入第二个表(学生),但它不起作用。这就是我所做的:
<?php
$course_name = // the value of the field for the course name
$student_name = // The first name of the student
$student_age = // The age of the student
$last_id = // The last id of table courses
if(isset($_POST['submit1'])){
$query1 = "INSERT INTO courses (course_name)VALUES ('$course_name')";
if ($object->query($query1) === true){
$last_id = LAST_INSERT_ID();
$good = "the course has been created";
}
else{
$bad = "Error: " .$query1.$object->error;
}
}
if(isset($_POST['submit2'])){
$query2 = "INSERT INTO students (course_id,student_name, student_age)VALUES ('last_id','$student_name','student_age')";
if ($object->query($query2) === true){
$good = "the student has been created";
}
else{
$bad = "Error: " .$query2.$object->error;
}
}
?>
我不知道为什么它不起作用。
答案 0 :(得分:1)
你没有提到你是否正在使用PDO或mysqli等等。如果它是mysqli它$mysqli->insert_id;
if ($object->query($query1) === true){
$last_id = $object->insert_id
$good = "the course has been created";
}
OTH,如果你使用的是PDO lastInsertId
if ($object->query($query1) === true){
$last_id = $object->lastInsertId()
$good = "the course has been created";
}