douxian0008 2014-06-16 05:52 采纳率: 0%
浏览 41
已采纳

查找多个插入查询的auto_increment值

I have a form to enter a student's name and his marks.


I have two tables :

student

student_id | student_name
         1 | John
         2 | Doe

marks

student_id | mark
         1 | 80
         2 | 90

The Student Name field has an autocomplete function which checks the student table if the student already exists.

Now, if I type J in the Student Name field in the form, it shows John. If I click John, and then enter a mark(say 50) in the Mark field and submit the form, the student table remain untouched, while the marks table gets inserted with a new row (1 | 50), where 1 is the student_id of the selected student (In this case, id of John).

Now, if I type a new name (say, Rae) in the Student Name field, and some mark(say 75) in the Mark field, both tables should get inserted with a new row on form submit. i.e., student table should now have a new row (3 | Rae) and marks table should have a new row (3 | 75)

MY PROBLEM IS, since student_id is an auto_incremented value from student, the student_id field in the marks table get a value 0 while entering a new student (In this case, Rae), which insert the row as (0 | 75) instead of my requirement (3 | 75).

As far as I know, mysqli_insert_id() can be used here, but I'm using three insert statements in a go. The above mentioned two insert queries are second and third. The auto_increment value from the first insert is being used for some other purpose using the mysqli_insert_id() command.

  • 写回答

1条回答 默认 最新

  • dshyu6866 2014-06-16 06:03
    关注

    Use LAST_INSERT_ID() within your query to get the new ID. For example:

    INSERT INTO student (student_name) VALUES ('John');
    INSERT INTO marks (student_id, mark) VALUES (LAST_INSERT_ID(), 74);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧