سؤال

I want to store the data from several curl calls to an initial table, but last insert id is inserting wrong info

Query 1 inserts data into table

table1

   id name      email      valuereturn
   1   val     val@email.com       0

I then post data 3 times to my system and log it

table2

    id  name    system  valuereturn
    1   val      5       0
    2   val      0       0
    3   val      0       0

the max value returned from my system i want to update table 1

update table1 
set valuereturn = '5' 
where id = LAST_INSERT_ID()

does not work because last insert id is 3 from table2, how can I use something like last_insert_id(Table1)?

i want to update my

هل كانت مفيدة؟

المحلول

Well, you can't. You have to retrieve and remember it in a PHP variable.

Or go for Saharsh's solution and remember it in a MySQL variable.

نصائح أخرى

Store that LAST_INSERT_ID() of table1 in a variable and than use that variable in update query.

INSERT INTO table1(name) values ('Saharsh');
SELECT LAST_INSERT_ID() INTO @table1Id;

INSERT INTO table2(name, table1id) values ('Saharsh', @table1Id);
UPDATE table1 SET valuereturn = '5' WHERE id = @table1Id;

In PHP I assume you use the following code:

<?php
  connect_db();
  insert_first_query_to_table1();
  insert_second_query_to_table2();
  update_query_setting(last_insert_id());
?>

If that's the case, I suggest you to use a temp variable to store the last_insert_id.

<?php
  connect_db();
  insert_first_query_to_table1();
  $setVal = last_insert_id();
  insert_second_query_to_table2();
  update_query_setting($setVal);
?>

Hope this helps.

PS: This is a pseudo code!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top