Access last created row in PHP / MySQL

How to access the row that was just inserted into the database 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 a new line in bar ()?

+3
source share
4 answers

If the id column is an automatic increment, you can use mysql_insert_id :

Gets the identifier generated for AUTO_INCREMENTthe previous one INSERT.


The example in the manual is as follows:

$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());
+10
source

You can get the last item inserted with mysql_insert_id ()

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

+3
source

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

SELECT rows from table where id = last_inserted_id
+3
source

Using the PHP function mysql_insert_id()will return the identifier of the last line entered.

+1
source

Source: https://habr.com/ru/post/1716511/


All Articles