2016-08-07 36 views
-1

我有两个提交按钮,它们从两个表单中获取值并将它们插入到数据库中。问题是我需要从第一个表(课程)中获取最后一个插入的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; 
       } 
    } 
?> 

我不知道为什么它不起作用。

+0

一件事,你在这些' 'last_id', '$ student_name' 的2冷落'$'迹象, 'student_age' '在你的价值中。如果这是你的实际代码,那很可能是你的代码失败的原因。这些应该读作''$ last_id','$ student_name','$ student_age''。所以,做出这些改变,然后回来告诉我们问题是什么;你从来没有提到什么不起作用。 –

+0

我们也不知道您的变量和/或POST数组是否具有值,以及它们是否正确。我不会一直坚持几个小时,所以你需要直接ping我。 –

+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"; 
} 
+0

这是我正在使用的mysqli。我不知道它为什么仍然不起作用的原因。谢谢你的帮助。 – princesse

+0

请不要用这个词不起作用。总是给出完整的错误 – e4c5

+0

早上好!这是它甚至不会显示任何错误的问题。 – princesse