I have 2 tables. In one table I add events, ID are auto-increment. The second table contains personal events.
So if I create event, it adds to both tables.
Here down below is a example of my code. So first of all I add a new event to general table. Then I want to add the same event to schedule table, but I need to get the ID of just added event. So I execute that second query.
Is there any optimized way how to do this or at least get the ID of just added event without extra query?
mysql_query("INSERT INTO events (title, description, user) VALUES ('$title', '$description', '".$user['id']."')");
$id = mysql_fetch_array(mysql_query("SELECT id FROM events WHERE user='".$user['id']."' ORDER BY date_added DESC LIMIT 1"));
mysql_query("INSERT INTO schedule (uid, event) VALUES ('".$user['id']."', '".$id['id']."')") or die(mysql_error());
mysql_insert_id()is what you are after, I think…You could also use the MySQL native
LAST_INSERT_ID()in your secondINSERTquery:…and skip retrieving the ID in PHP altogether.