du1108 2014-05-14 10:02
浏览 21
已采纳

从同一数据集执行2个sql语句

I want to insert data into two different tables at the same time using PHP. I have an android application with an interface for entering students information. This information includes student name, student year, course name and grade.

I have 2 tables, The first table has columns for id, student year, student class. The id column is set to auto-increment. The second table has also its own id column also set to auto-increment and in addition has columns for course, grade and id from the first table. This of course is a foreign key in this second table.

My question now is, after inserting student name and student year into the first table, how can I make use of that row id so that it will be a foreign key while inserting the remaining data i.e 2nd table id(already set to auto-increment), course and grade.

For instance, in my android app, if I entered student name as John David, student year as third year, course name as Geo 101 and grade as B, I want to save the name and the year into the first table and after successful execution of that, the student course name and grade should be entered into the second table and the id from the first table for that row that has just been entered should be inserted into the second table also under the column id which is a foreign key referencing first table id.

I just need an idea of how to go through this not necessarily a code.

Thanks.

  • 写回答

1条回答 默认 最新

  • duande1146 2014-05-14 10:10
    关注

    Something like this:

      INSERT INTO foo (auto,text)
        VALUES(NULL,'text');         # generate ID by inserting NULL
      INSERT INTO foo2 (id,text)
        VALUES(LAST_INSERT_ID(),'text');  # use ID in second table
    

    As per documentation in http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

    And for some PHP specific tutorial on your question checkout: http://www.php.net/manual/en/function.mysql-insert-id.php

    I am not gonna try to write you PHP code 'cause I have not done it for years :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。