Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

MySQL last_insert_id

Featured Replies

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. :)

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.

  • 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

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.