Hello Guys today’s tutorial is all about How to Get the Last ID Saved in MySQL Using PHP The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table. Let’s get started:
1. Open PHPMyAdmin.
2. Create a database and name it as “getlasid”.
3. Create database connection and save it.
4.Then Create a form name it index.php and put this code
<!DOCTYPE html> <html> <head> <title>How to Get the Last ID Saved in MySQL Using PHP</title> </head> <body> <h2>Add Form:</h2> <form method="POST"> <label>Firstname:</label><input type="text" name="firstname"> <label>Lastname:</label><input type="text" name="lastname"> <label>Address:</label><input type="text" name="address"> <input type="submit" value="Add" name="submit"> </form> <?php $id=""; $row['firstname']=""; $row['lastname']=""; $row['address']=""; if (isset($_POST['submit'])){ $firstname=$_POST['firstname']; $lastname=$_POST['lastname']; $address=$_POST['address']; include('conn.php'); $conn->query("insert into `user` (firstname, lastname, address) values ('$firstname','$lastname','$address')"); $id = $conn->insert_id; $query=$conn->query("select * from `user` where userid='$id'"); $row = $query->fetch_assoc(); } ?> <h2>Last inserted Id: <?php echo $id; ?></h2> <h2>Data:</h2> <label>Firstname: </label> <?php echo $row['firstname']; ?><br> <label>Lastname: </label> <?php echo $row['lastname']; ?><br> <label>Address: </label> <?php echo $row['address']; ?> </body> </html>
<!DOCTYPE html>
<html>
<head>
<title>How to Get the Last ID Saved in MySQL Using PHP</title>
</head>
<body>
<h2>Add Form:</h2>
<form method="POST">
<label>Firstname:</label><input type="text" name="firstname">
<label>Lastname:</label><input type="text" name="lastname">
<label>Address:</label><input type="text" name="address">
<input type="submit" value="Add" name="submit">
</form>
<?php
$id="";
$row['firstname']="";
$row['lastname']="";
$row['address']="";
if (isset($_POST['submit'])){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$address=$_POST['address'];
include('conn.php');
$conn->query("insert into `user` (firstname, lastname, address) values ('$firstname','$lastname','$address')");
$id = $conn->insert_id;
$query=$conn->query("select * from `user` where userid='$id'");
$row = $query->fetch_assoc();
}
?>
<h2>Last inserted Id: <?php echo $id; ?></h2>
<h2>Data:</h2>
<label>Firstname: </label> <?php echo $row['firstname']; ?><br>
<label>Lastname: </label> <?php echo $row['lastname']; ?><br>
<label>Address: </label> <?php echo $row['address']; ?>
</body>
</html>
5.Lastly, Run and test the program!

If you have any comments or suggestions about the How to Get the Last ID Saved in MySQL Using PHP please message us directly.
Download Source Code here:
Other Articles you might read also:
Wow, great blog article.Much thanks again. Much obliged.