简体   繁体   中英

SQL return values of affected rows in last query?

I have an SQL query which inserts a new record into table1 . The records 'id' is the PK ( field1 ) and has the auto increment property:

INSERT INTO table1 (field2, field3) VALUES ("Hello", "World")

My next query (immediately afterwards) inserts a record into table2 , and requires the id of the row which was affected in the previous query.

INSERT INTO table2 (field2) VALUES (PKValueOfAffectedRowInPreviousQuery)

Is there a function which can return a result set for the rows affected in a query, something along the lines of $result = $stmt->return_affected_records() so that I could access this field1 value?

This is entirely different to returning the number of affected rows, which I know is received using $stmt->affected_rows . I'm concerned with the values within those records affected.

I think you could do this with a select in between these two insert s:

$value1 = "Hello";
$value2 = "World";

INSERT INTO table1 (field2, field3) VALUES ($value1,$value2);

$sql = "SELECT field1 FROM table1 WHERE field2 ='" . $value1 . "' AND field3 = '" . $value2 . "'"; 

Now you just have to extract the id from the result and make your second insert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM