Search code examples
mysqlvariablessetlast-insert-id

How do I use SET to create a LAST_INSERT_ID user-defined variables in mysql?


I need to insert values into multiple tables where the primary key (id) of the first table (users) is the foreign key (user_id) of subsequent tables (email etc.).

I worked out the following query in MySQL Workbench, which works perfectly fine there. However when I run it in the context of the website form that I'm developing I keep getting a syntax error message for the line: SET @nameID = LAST_INSERT_ID();

INSERT INTO users (first_name, last_name)
  VALUES('John', 'Doe');
SET @userID = LAST_INSERT_ID();
INSERT INTO email (user_id, email)
  VALUES(@userID,'[email protected]');
INSERT INTO phone_number (user_id, phone_number)
  VALUES(@userID, 4546254758);

I've spent a bit of time trying to workout what the issue is but haven't been able to come with an answer so far. Any help would be appreciated.

Edit: Updated code to show that by 'multiple' I mean more than two.


Solution

  • don't run all queries one shot , you should run one by one then it will work through php normally , try like this

        $mysqli = new mysqli('localhost', 'root', '', 'test');
        $mysqli->query("INSERT INTO users (first_name, last_name)
           VALUES('John8', 'Doe');" );
        $mysqli->query('SET @userID = LAST_INSERT_ID();' );
        $mysqli->query("INSERT INTO email (user_id,email) VALUES ( @userID 
           ,'[email protected]');" );