php last insert id code example

Example 1: get last inserted id in php

Example (MySQLi Procedural)
$last_id = mysqli_insert_id($conn);

Example 2: get id of record created php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example 3: pdo last id

Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.



<?php

try {

    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');



    $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");



    try {

        $dbh->beginTransaction();

        $tmt->execute( array('user', '[email protected]'));

        $dbh->commit();

        print $dbh->lastInsertId();

    } catch(PDOExecption $e) {

        $dbh->rollback();

        print "Error!: " . $e->getMessage() . "</br>";

    }

} catch( PDOExecption $e ) {

    print "Error!: " . $e->getMessage() . "</br>";

}

?>



When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.

Example 4: mysql get this inserted id php

$this_id = mysqli_insert_id($db);

Example 5: last_insert_id() php

<?php
// use mysql_insert_id():
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) { die('Impossible de se connecter : ' . mysql_error()); }
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('something')");
printf("last inserted id is %d\n", mysql_insert_id());
?>

Tags:

Sql Example