mysqli_stmt::$insert_id

mysqli_stmt_insert_id

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$insert_id -- mysqli_stmt_insert_id — Devuelve el valor generado para una columna AUTO_INCREMENT por la última consulta ejecutada

Descripción

Estilo orientado a objetos

Estilo procedimental

function mysqli_stmt_insert_id(mysqli_stmt $statement): int|string

Devuelve el ID generado por una consulta INSERT o UPDATE en una tabla con una columna que tiene el atributo AUTO_INCREMENT. En el caso de una consulta INSERT de varias filas, devuelve el primer valor generado automáticamente que se insertó con éxito. Si se utiliza LAST_INSERT_ID(expr) para establecer el valor de AUTO_INCREMENT, o en una consulta UPDATE, se devuelve en su lugar el valor de expr.

Devuelve 0 si la consulta no cambió ningún valor AUTO_INCREMENT.

Parámetros

statement

Solo estilo procedimental: Un objeto mysqli_stmt devuelto por mysqli_stmt_init().

Valores devueltos

El valor del campo AUTO_INCREMENT que fue modificado por la consulta. Devuelve cero si la consulta aún no se ha ejecutado o si no modificó ningún valor AUTO_INCREMENT.

El valor es específico del objeto de consulta. No se ve afectado por otras consultas ejecutadas en la misma conexión después de esta consulta, ni por las consultas emitidas mediante otras conexiones o clientes.

Nota:

Si el número es mayor que el valor máximo de un integer, será devuelto como un string.

Ejemplos

Ejemplo #1 Ejemplo con mysqli_stmt::$insert_id

Estilo orientado a objetos

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District, Population) VALUES (?, ?, ?, ?)");

$name = 'Stuttgart';
$countryCode = 'DEU';
$district = 'Stuttgart';
$population = 617000;
$stmt->bind_param('sssi', $name, $countryCode, $district, $population);
$stmt->execute();

printf("El nuevo registro tiene ID %d.\n", $stmt->insert_id);

Estilo procedimental

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District, Population) VALUES (?, ?, ?, ?)");

$name = 'Stuttgart';
$countryCode = 'DEU';
$district = 'Stuttgart';
$population = 617000;
mysqli_stmt_bind_param($stmt, 'sssi', $name, $countryCode, $district, $population);
mysqli_stmt_execute($stmt);

printf("El nuevo registro tiene ID %d.\n", mysqli_stmt_insert_id($stmt));

Los ejemplos anteriores mostrarán:

El nuevo registro tiene ID 1.

Véase también

+add a note

User Contributed Notes 2 notes

up
7
hgernhardt at tcnewengland dot org
15 years ago
It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement.  In practice, it appears that the first insertion ID is returned.  If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.
up
3
Aurelien Marchand
11 years ago
for those with zerofilled IDs beware as mysqli_stmt::$insert_id will return an integer. In other words, if the ID returned from your query was #000099, the value produced by mysqli_stmt::$insert_id is now #99.

I have not found a way to fix this beside using sprintf('%06d',$id) but this assumes you know in advance the size of the ID beforehand.