Get last inserted record ID mySQL using PHP

Get last inserted record ID mySQL using PHP

Today, We want to share with you Get last inserted record ID mySQL using PHP.
In this post we will show you Get last inserted record ID mySQL using PHP, hear for Get last inserted record ID mySQL using PHP we will give you demo and example for implement.
In this post, we will learn about Get last inserted record ID mySQL using PHP with an example.

If we perform an mysqli using Database INSERT statement or UPDATE statement on a table(mysql or mysqli) with an AUTO_INCREMENT(primary fields) field, we can get the ID(directly get last id) of the last inserted/updated(statement) record immediately.

PHP Get ID of Last Inserted Record

mysqli::$insert_id or mysqli_insert_id — It’s Returns the auto generated(uniq) id used in the latest query in PHP functions

No Function Support Used functions
1 MySQLi Object-oriented $last_id = $conn->insert_id;
2 MySQLi Procedural $last_id = mysqli_insert_id($conn);
3 PDO – Example $last_id = $conn->lastInsertId();
4 Mysql – Example $last_id =mysql_insert_id();

MySQLi Object-oriented – $last_id = $conn->insert_id;

$your_last_id = $conn->insert_id;

 query($sql_query) === TRUE) {
/*
 * RETURN LAST INSERT ID
 * Returns the last record's ID that was inserted into table 'mytable'
 */
    $your_last_id = $conn->insert_id;
    echo "your New record  created same successfully. your Last inserted ID is: " . $your_last_id;
} else {
    echo "Error Generate: " . $sql_query . "
" . $conn->error; } $conn->close(); ?>

MySQLi Procedural – mysqli_insert_id($conn);

query($sql_query) === TRUE) {
/*
 * RETURN LAST INSERT ID
 * Returns the last record's ID that was inserted into table 'mytable'
 */
    $your_last_id = mysqli_insert_id($conn);
    echo "your New record  created same successfully. your Last inserted ID is: " . $your_last_id;
} else {
    echo "Error Generate: " . $sql_query . "
" . $conn->error; } $conn->close(); ?>

MySQLi PDO – $conn->lastInsertId();

exec($sql_pdo);
	/*
 * RETURN LAST INSERT ID
 * Returns the last record's ID that was inserted into table 'mytable'
 */
    $your_last_id = $conn->lastInsertId();
    echo "your New record  created same successfully. your Last inserted ID is: " . $your_last_id;
    }
	catch(PDOException $e)
    {
    echo $sql_pdo . "
" . $e->getMessage(); } ?>

View Demo

We hope you get an idea about Get last inserted record ID mySQL using PHP
We would like to have feedback on my Information blog .
Your valuable any feedback, Good question, Inspirational Quotes, or Motivational comments about this article are always welcome.
If you liked this post, Please don’t forget to share this as Well as Like FaceBook Page.

We hope This Post can help you…….Good Luck!.

Leave a Comment