How to get last inserted record in 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 ('HackTheStuff', '[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 ('Meniya', '[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.

Tags: