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

落花浮王杯 提交于 2019-12-01 09:53:37

问题


I am working on an events calendar using PHP and MySQL (V5.1) where the admin would add an event, and then an attendance list for that event would be created as well. I have three tables: events, attendance and members. So far I can create the event using information that is entered thorugh a PHP form. I'm trying to update the attendance table by inserting the event id from the event that has just been created, as well as pulling in the list of members (using their member ID) from the members table. Nothing is being added to attendance the table though. Can someone let me know what I should I be doing differently?

Some of the fields I am using in the tables:
Events: event_ID (Primary key, auto-increment), name, location, date
Attendance: attendance_ID (Primary key, auto-increment), event_ID, member_ID, attending
Members: member_ID (Primary key, auto-increment), name, email

enter code here

Here is the code:

mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");

$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)."')");

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

if ($query1 and $query2) { 
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");

}


回答1:


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.




回答2:


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") ;



回答3:


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");


来源:https://stackoverflow.com/questions/14924569/two-inserts-in-php-mysql-using-last-insert-id-and-rows-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!