I have received many statements that the insert_id property has a bug because it "works sometimes". Keep in mind that when using the OOP approach, the actual instantiation of the mysqli class will hold the insert_id.
The following code will return nothing.
<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
echo 'The ID is: '.$result->insert_id;
}
?>
This is because the insert_id property doesn't belong to the result, but rather the actual mysqli class. This would work:
<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
echo 'The ID is: '.$mysqli->insert_id;
}
?>
mysqli::$insert_id
mysqli_insert_id
(PHP 5)
mysqli::$insert_id -- mysqli_insert_id — Devuelve el id autogenerado que se utilizó en la última consulta
Descripción
Estilo orientado a objetos
Estilo por procedimientos
La función mysqli_insert_id() devuelve el ID generado por una consulta en una tabla con una columna que tenga el atributo AUTO_INCREMENT. Si la última consulta no fue una sentencia INSERT o UPDATE o si la tabla modificada no tiene una columna con el atributo AUTO_INCREMENT, está función devolverá cero.
Nota:
Realizar una sentencia INTERT o UPDATE usando la función LAST_INSERT_ID() modificará el valor retornado por la función mysqli_insert_id().
Parámetros
-
link -
Sólo estilo por procediminetos: Un identificador de enlace devuelto por mysqli_connect() o mysqli_init()
Valores devueltos
El valor de el campo AUTO_INCREMENT que fué actualizado por la consulta anterior. Devuelve cero si no hubo una consulta previa en la conexión o si la consulta no actualiza un valor AUTO_INCREMENT.
Nota:
Si el número es mayor que el valor máximo int, mysqli_insert_id() retornará un string.
Ejemplos
Ejemplo #1 Ejemplo de $mysqli->insert_id
Estilo orientado a objetos
<?php
$mysqli = new mysqli("localhost", "mi_usuario", "mi_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Error de conexión: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("Nuevo registro con el id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Estilo por procedimientos
<?php
$link = mysqli_connect("localhost", "mi_usuario", "mi_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Error de conexión: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);
printf ("Nuevo registro con el id %d.\n", mysqli_insert_id($link));
/* drop table */
mysqli_query($link, "DROP TABLE myCity");
/* close connection */
mysqli_close($link);
?>
El resultado de los ejemplos serían:
Nuevo registro con el id 1.
When running extended inserts on a table with an AUTO_INCREMENT field, the value of mysqli_insert_id() will equal the value of the *first* row inserted, not the last, as you might expect.
<?
//mytable has an auto_increment field
$db->query("INSERT INTO mytable (field1,field2,field3) VALUES ('val1','val2','val3'),
('val1','val2','val3'),
('val1','val2','val3')");
echo $db->insert_id; //will echo the id of the FIRST row inserted
?>
Watch out for the oo-style use of $db->insert_id. When the insert_id exceeds 2^31 (2147483648) fetching the insert id renders a wrong, too large number. You better use the procedural mysqli_insert_id( $db ) instead.
[EDIT by danbrown AT php DOT net: This is another prime example of the limits of 32-bit signed integers.]
I was having problems with getting the inserted id, and did a bit of testing. It ended up that if you commit a transaction before getting the last inserted id, it returns 0 every time, but if you get the last inserted id before committing the transaction, you get the correct value.
Some people are wondering how to get the ids of the rows inserted with loop. Here is it:
<?php
// stmt_init ...
for (;;;) {
// do some things...
$stmt->execute();
$ids[] = $mysqli->insert_id;
}
?>
Note that if you Call a MySQL stored procedure to insert a new record and then reference $db->insert_id; you will get 0 back, not the last inserted ID.
It is therefore necessary to add a line to your MySQL Stored Procedure such as
select last_insert_id() as intRecordKey;
after the insert so that the query will return the new key value.
Then in your php code you can use the following
<?php
$objInsertResult = $db->query($strSQL);
$objInsertRow = $objInsertResult->fetch_object();
$intRecordKey = $objInsertRow->intRecordKey;
?>
It would however be nice if $db->insert_id did return the last insert ID following a stored procedure call.
