English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

Último ID insertado MySQL en PHP

In this tutorial, you will learn how to use PHP to retrieve the unique ID of the last inserted row from a MySQL database table.

How to Get the ID of the Last Inserted Row

In " PHP MySQL InsertIn this chapter, you have learned that each time a new record or row is inserted into the table, MySQL automatically generates a unique ID for the column with AUTO_INCREMENT. However, in some cases, you need to insert the automatically generated ID into the second table. In these cases, you can use the PHP mysqli_insert_id() function to retrieve the most recently generated ID, as shown in the following example.

In this example, we will use the one inPHP MySQL Create Tablethe same chapter created inpersonaltable, which has four columnsid,first_name,last_nameandemail, whereidis the primary key column and marked with the AUTO_INCREMENT flag.

Example: Procedural Approach

<?php
/* intentar conectar al servidor MySQL. Supongamos que está ejecutando MySQL.
servidor con configuración predeterminada (usuario sin contraseña "root")*/
$link = mysqli_connect("localhost", "root", "", "demo");
 
//verificar la conexión
if ($link === false) {
    die("Error: Unable to connect. ". mysqli_connect_error());
}
 
//intentar ejecutar la consulta de inserción
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', '[email protected]')";
if (mysqli_query($link, ''$sql'')) {
    //obtener el último ID insertado
    $last_id = mysqli_insert_id($link);
    echo "se ha insertado el registro con éxito. El último ID insertado es: ". $last_id;
} else{
    echo "error: no se puede ejecutar $sql. ". mysqli_error($link);
}
 
//cerrar conexión
mysqli_close($link);
?>

ejemplo: método orientado a objetos

<?php
/* intentar conectar al servidor MySQL. Supongamos que está ejecutando MySQL.
servidor con configuración predeterminada (usuario sin contraseña "root")*/
$mysqli = new mysqli("localhost", "root", "", "demo");
 
//verificar la conexión
if($mysqli === false){
    die("error: no se puede conectar. ". $mysqli->connect_error);
}
 
// intentar ejecutar la consulta de inserción
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', '[email protected]')";
if($mysqli->query($sql) === true){
    //obtener el último ID insertado
    $last_id = $mysqli->insert_id;
    echo "se ha insertado el registro con éxito. El último ID insertado es: ". $last_id;
} else{
    echo "error: no se puede ejecutar $sql. ". $mysqli->error;
}
 
//cerrar conexión
$mysqli->close();
?>

ejemplo: método PDO

<?php
/* intentar conectar al servidor MySQL. Supongamos que está ejecutando MySQL.
servidor con configuración predeterminada (usuario sin contraseña "root")*/
try{
    $pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
    //establecer el modo de error de PDO en excepción
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("error: no se puede conectar. ". $e->getMessage());
}
 
//intentar ejecutar la consulta de inserción
try{
    $sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', '[email protected]')";    
    $pdo->exec($sql);
    $last_id = $pdo->lastInsertId();
    echo "se ha insertado el registro con éxito. El último ID insertado es: ". $last_id;
} catch(PDOException $e){
    die("error: no se puede ejecutar $sql. ". $e->getMessage());
}
 
//cerrar conexión
unset($pdo);
?>