How to get all last inserted row ids in mysql-php?

Is there any efficient way to get all added automatically incremented row identifiers from mysql database using php? Suppose I don’t know how many lines should be inserted in the package, but I need all their identifiers after insertion.

After Googling, I did not find an effective way to do this, so I'm not sure if this is possible. I can keep track of this, but you need to hit the database several times to get the identifiers.

$data = array (
array(1,2),
array(3,4),
array(5,6)
);

$ids = array();

foreach ($data as $item) {
   $sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
   mysql_query ($sql);
   $ids[] = mysql_insert_id();
}

thank

+5
source share
5 answers

your code is next to a complete solution.

$data = array (
array(1,2),
array(3,4),
array(5,6)
);

$ids = array();

foreach ($data as $item) {
   $sql = "INSERT INTO `table` (`a`, `b`) VALUES ('{$item[0]}' ,'{$item[1]}');";
   mysql_query ($sql) or mysql_error();
   $ids[] = mysql_insert_id();
}

var_dump($ids);

If the question is about a performance issue, then another solution might be

foreach ($data as $item) {
   $sql = "INSERT INTO `table`.`table` (`a`, `b`) VALUES ('{$item[0]}' ,'{$item[1]}');";
   mysql_query ($sql) or mysql_error();
}

$last_id = mysql_insert_id();
$total = count($data);
for($i = 0; $i <= $total; $i++){
    $ids[] = $total-$i;
}

sql.

+1

Mysql id, , (). , :

  • .

  • , mysql , , , (, , ).

, n1, , , INSERT blah blah ON DUPLICATE KEY, 2 ( ) , , , .

, mysql_, , mysqli pdo

+1

auto_incremented "", - , id , , , .

:

$sql = "SELECT id FROM table ORDER BY id DESC LIMIT 1";
    // get maximal value before insert

$sql = "SELECT id FROM table WHERE id > :last_id"; // get all new

.

0

When I need to track batches of entries, I have an extra field in the table, usually indicated as a stamp or something like that. When entries are inserted, the stamp field is then filled with the current timestamp specified by the time () function. Then each batch can be tracked, no matter how old she is. In addition, saving timestamps is an easy way to get the exact time when they were added.

0
source

Getting the id of the last insert id

    <?php

$conn = mysql_connect('localhost', 'user', 'password');

mysql_select_db('test');

$data = array (
array(1,2),
array(3,4),
array(5,6)
);

$ids = array();

foreach ($data as $item) {

   $sql = 'insert into testtable (a,b) values ('.$item[0].','.$item[1].')';   
   mysql_query ($sql, $conn);
   $id[] = mysql_insert_id($conn);
}
-1
source

All Articles