views:

53

answers:

2

I am using MySQL. I need to insert one row into a table first, then I need to get the id of the inserted row. The code looks somewhat like the following:

insert into mytable (column2, column3, column4) values('value2','value3','value4')or die(mysql_error());

Column1

is the

primary key

and it is auto-increment. So how to get the value of

column1

in the previous operation?

+1  A: 

You are probably looking for the mysql_insert_id function :

Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

Or mysqli_insert_id or PDO::lastInsertId, depending on which extension you use to access your MySQL database.

Pascal MARTIN
+1  A: 

You can use mysql_insert_id. From the docs:

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
jheddings