Get Last Inserted Record ID in PHP

  372 views   7 months ago PHP

Any table has id field which is AUTO_INCREMENT. So when the record inserted, id is generated automatically generated according to previous row. But sometimes you need to get id of the last inserted row in relattionship tables.

In this article, we will learn how to get last inserted records id in PHP. PHP has in-build function mysqli_insert_id() which returns the last inserted record.

Example:

<?php

$conn = new mysqli("localhost", "mysql_username", "mysql_password", "mysql_dbname");

if (mysqli_connect_errno()) {
    echo(mysqli_connect_error());
    exit();
}

mysqli_query($conn, "INSERT INTO users (name, email, password) VALUES ('Harsukh Makwana', '[email protected]', '123456')");

// id of last inserted record
echo(mysqli_insert_id($conn));

mysqli_close($conn);

The other way is using connection's insert_id property.

Example:

<?php

$conn = new mysqli("localhost", "mysql_username", "mysql_password", "mysql_dbname");

if ($conn->connect_errno) {
    echo($conn->connect_error);
    exit();
}

$conn->query("INSERT INTO users (name, email, password) VALUES ('Harsukh Makwana', '[email protected]', '123456')");

// id of last inserted record
echo($conn->insert_id);

$conn->close();

This way you can get last inserted row's id. With its help, you can also get row using WHERE query like:

SELECT * FROM users WHERE id = 5;

Thank you for giving time in reading article. I hope it helped you in your work.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]