March 13, 201115 yr Hi, I'm having some trouble with last_insert_id and @last in MySQL. First time trying to reference two tables in one go before. As far as I can tell, there is no error with this: $headphone_query = "INSERT INTO headphone (headphone_id, brand, model, picture, type_of_headphone, color, length, both_buds, noise_cancelling) VALUES (NULL, '$_POST[brand]', '$_POST[model]', '$new_url', '$_POST[type_of_headphone]', '$_POST[colour]', '$_POST[length]', '$_POST[both_buds]', '$_POST[noise_cancelling]'); SELECT @last := LAST_INSERT_ID(); INSERT INTO location (room, campus, lost_found, headphone_id) VALUES ('$_POST[location]', '$_POST[campus]', 'lost', @last); INSERT INTO person (name, email, student_id, finder_loser, headphone_id) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[student_number]', 'loser', @last); "; But MySQL says otherwise, [quot]Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @last := LAST_INSERT_ID(); INSERT INTO location (room, campus, lost_f' at line 5 I've checked with the manual and can see no difference, so if someone can shed some light, much appreciated. Cheers.
March 13, 201115 yr I'm guessing you're running this through mysql_query()? If I remember rightly it will only execute one query per call, i.e. to your first ';'. I'd split them out, and use mysql_insert_id(). And better still if you're using innodb additionally wrap all the queries in a transaction to ensure either they all work successfully or none of them do.
March 15, 201115 yr Author I'm guessing you're running this through mysql_query()? If I remember rightly it will only execute one query per call, i.e. to your first ';'. I'd split them out, and use mysql_insert_id(). And better still if you're using innodb additionally wrap all the queries in a transaction to ensure either they all work successfully or none of them do. That's the ticket. All sorted.
Create an account or sign in to comment