我有两个提交按钮,它们从两个表单中获取值并将它们插入到数据库中。问题是我需要从第一个表(课程)中获取最后一个插入的ID插入第二个表(学生),但它不起作用。这是我做的:LAST_INSERT_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;
}
}
?>
我不知道为什么它不起作用。
一件事,你在这些' 'last_id', '$ student_name' 的2冷落'$'迹象, 'student_age' '在你的价值中。如果这是你的实际代码,那很可能是你的代码失败的原因。这些应该读作''$ last_id','$ student_name','$ student_age''。所以,做出这些改变,然后回来告诉我们问题是什么;你从来没有提到什么不起作用。 –
我们也不知道您的变量和/或POST数组是否具有值,以及它们是否正确。我不会一直坚持几个小时,所以你需要直接ping我。 –
我看到你有一个(坏)习惯没有回应你的问题留下的评论。我已经放弃了这个,请向下面给你留下一个答案的人问一下,我会通过这个。祝你好运。 –