wolfvilleian
wolfvilleian

Reputation: 23

How to get result of Insert

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.

Table A:

id       Name
----------------
1        Name1
2        Name2

Table B:

id       Name      Parent
-------------------------
1        John      1

What happens:

Upvotes: 2

Views: 8699

Answers (3)

webbiedave
webbiedave

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

Sarfraz
Sarfraz

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

poke
poke

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

Related Questions