Two inserts in PHP/MySQL using LAST_INSERT_ID() and rows from another table

放肆的年华 提交于 2019-12-01 12:59:48

A couple of important points. First, if you getting your last insert ID you should execute LOCK and UNLOCK queries first:

  • LOCK TABLES events WRITE;
  • UNLOCK TABLES

Second, you can use the mysqli_insert_id() method to get the ID of the last insert. This means that you must have an AUTO_INCREMENT field in the table you are inserting.

You could use mysql_insert_id()

$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");

$insert_id = mysql_insert_id() ;

$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT {$insert_id}, members.member_ID FROM members") ;

Put VALUES into $query2 to form a correct SQL-statement:

$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) **VALUES (**SELECT LAST_INSERT_ID(), members.member_ID FROM members");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!