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.
<?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.
<?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.
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]
Paypal Card Payment REST API integration in Laravel 6
In this article we will share with you h...How to get and set text in HTML elements in Javascript
I have noticed that newer Javscript deve...How to check or uncheck a checkbox dynamically using jQuery
Use the jQuery prop() method You can...Laravel 8 Send Mail using Mailtrap
Today, I would relish to show you larave...Build a Basic React App
In this article, we will share with you...