Get the unique id of the last inserted row in PHP MYSQL
×


Get the unique id of the last inserted row in PHP MySQL

4135

If you want to access the unique id of last inserted or updated row in a MYSQL table, you can use mysqli_insert_id() function. The column which you want to access through this method should be AUTO incremented.

Example:

Create Table:

<?php
//First connect to the database and then create a table.
$connect=mysqli_connect("host","username","password","databasename"); OR die ("connection failed");
$query="CREATE TABLE  student (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(25) NOT NULL,
city VARCHAR(25) NOT NULL
)";
$result=mysqli_query($connect,$query);
?>

Insert data into the table and get last unique id

<?php
$sql="INSERT INTO student(name, city) VALUES('Vihaan','Delhi')";
// student is table name
$result=mysqli_query($conn,$sql);
if ($result)
{
echo "Record Created Successfully";
$id = mysqli_insert_id($conn);
echo "<br>"."last inserted id is ".$id;
}else
{
echo "Insertion Failed";
}
?>

Output:




Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments