Reputation: 23
This is a fairly basic question, I currently have two tables and in the second table there is a foreign key column for table A
.
id Name
----------------
1 Name1
2 Name2
id Name Parent
-------------------------
1 John 1
What happens:
Name1
into Table A
and mysql inserts the id.John
into Table B
AND set Parent
to be the id
of the query that was just inserted.Upvotes: 2
Views: 8699
Reputation: 48897
After the first insert, you can do:
$res = mysql_query('SELECT LAST_INSERT_ID()');
$row = mysql_fetch_array($res);
$lastInsertId = $row[0];
Alternatively, you can use mysql_insert_id. However, from the manual:
mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query.
Because of this, the first method I listed is preferred if your column uses -- or may use in the future -- BIGINT
.
Upvotes: 4
Reputation: 382656
You can use mysql_insert_id()
to get the last inserted id.
mysql_insert_id — Get the ID generated in the last query
Caution:
mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.
Example:
mysql_query("INSERT INTO ..........");
printf("Last inserted record has id %d\n", mysql_insert_id());
Upvotes: 3
Reputation: 387547
After executing the INSERT
query with mysql_query
, you can use mysql_insert_id
to get the ID that was used for the previously inserted row.
Upvotes: 2