tags:

views:

153

answers:

4

How to access the row which has just been inserted into a DB with PHP/MySQL?

I have:

    $sql = 'INSERT INTO `jos_db`.`jos_sections` (`id`,  `name`) VALUES (NULL, \'foo\')';
    mysql_query($sql, $dbi);

    bar();

How do I access the new row in bar()?

+8  A: 

If you 'id' column is an auto-increment, you can use mysql_insert_id :

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


The example given in the manual looks like this :

$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());
Pascal MARTIN
+3  A: 

You can get the last item inserted with mysql_insert_id()

http://us.php.net/manual/en/function.mysql-insert-id.php

Tim
+3  A: 

Use mysql_insert_id() function to select last row inserted in database.

SELECT rows from table where id = last_inserted_id
Mohamed
+1  A: 

Using the PHP function mysql_insert_id() function will return the id of the last row you inserted.

Victor