0

I have two tables as follow (just an example) :

|    Table1      |      |    Table2      |
------------------      ------------------
| id_table1 (pk) |      | id_table1 (pk) |
| foo            |      | id_table1 (fk) |
|                |      | bar            |

I need to insert a row in table1, then get the last inserted id and then insert a new row in the table2.
I'm using PDO with PHP and I want to do that in a single request.
But I also would like to retrieve the "first last_inserted_id" that I stored in a variable.
So what I did is :

$q = $db->query(
   'INSERT INTO table1 (foo)
    VALUES ("any");

    SET @id = LAST_INSERT_ID();

    INSERT INTO table2 (id_table1, bar)
    VALUES (@id, "any");

    SELECT @id;'
);

But unfortunately, when I fetch the result, I get false.

So what am I doing wrong ?
Is there a way to get an SQL variable ?

user3292788
  • 407
  • 1
  • 6
  • 15

0 Answers0