Вопрос

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

}

Это было полезно?

Решение 2

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");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top