get the ;last id of my sql code example

Example 1: 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 2: mysql get last inserted id

-- To get the last inserted auto-increment row ID: --
SELECT LAST_INSERT_ID( optional_expression )

-- If you have just inserted it using a command in C# use: --
int lastId = (Int32)yourCommand.LastInsertedId;

Tags:

Sql Example