Code has been added to clipboard!

How to Acquire MySQL Last Insert ID and Keep Track of Your Data Easily

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

We have covered the basics on how to store data in your databases. However, when you get into it, it might get hard to keep track of your data entries. Getting MySQL last insert ID is a useful function that lets you quickly and easily retrieve the ID of the last record you added to your database.

You can make MySQL get last insert ID by merely using a few simple statements, such as mysql_insert_id(). In this tutorial, we will provide code examples, illustrating the ID retrieval process using MySQLi and POD.

Additionally, we will explain other functions to apply when you want to get the ID of the latest record. For instance, echo statement is used to output the result.

MySQL Last Insert ID: Main Tips

  • PHP allows you to get the ID of the record inserted last.
  • This process helps you track the number of records you currently have in a table.
  • One of the most common ways to get MySQL last insert ID is using the mysql_insert_id() statement.

Ways to Retrieve ID: Code Examples

You might remember from our previous lessons that when a table includes an AUTO_INCREMENT column, MySQL generates the ID automatically. Remember that when you are using insert or update functions.

Let's look at a piece of script meant to create a table called users. You can see the column user_id is set to AUTO_INCREMENT:

CREATE TABLE users ( user_id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, username VARCHAR(40) NOT NULL, password VARCHAR(40) NOT NULL, email VARCHAR(60), register_date TIMESTAMP )

In the code examples provided below, you will see how we add a line of code to retrieve MySQL last insert ID. We use echo statement to display it.

Just like in our previous lessons on how to insert and delete table data, the three examples represent three database connection types. You will see how to perform MySQLi object oriented, MySQLi procedural and PDO last insert ID search.

Let's start with getting the MySQL last inserted ID using MySQLi object-oriented connection:

Example
<?php
  $host = 'host';
  $user = 'user';
  $pass = 'pass';
  $db = 'db';
  // Create connection
  $conn = new mysqli($host, $user, $pass, $db);  	
  // Check connection  	
  if ($conn->connect_error) {      
    die("Failed to connect: " . $conn->connect_error);
  }
  $sql = "INSERT INTO users (username, password, email) VALUES ('Johny', 'Dawkins', 'johny@example.com')";  	
  if ($conn->query($sql) === TRUE) { 
    $latest_id = $conn->insert_id;    
    echo "Insert successful. Latest ID is: " . $latest_id;
  } else { 
    echo "Error: " . $sql . "<br>" . $conn->error;
  }
  $conn->close();  
?>

If you are using MySQLi procedural connection, you can make MySQL get last insert ID by simply using mysql_insert_id() statement:

Example
<?php
  $host = 'host';
  $user = 'user';
  $pass = 'pass';
  $db = 'db';
  // Create connection  
  $conn = mysqli_connect($host, $user, $host, $db);  	
  // Check connection  	
  if (!$conn) { 
    die("Failed to connect: " . mysqli_connect_error());
  }
  $sql = "INSERT INTO users (username, password, email) VALUES ('Johny', 'Dawkins', 'johny@example.com')";  	
  if (mysqli_query($conn, $sql)) { 
    $latest_id =  mysqli_insert_id($conn);    
    echo "Insert successful. Latest ID is: " . $latest_id;
  } else { 
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
  }
  mysqli_close($conn);  
?>

In PDO last insert ID can be retrieved this way:

Example
<?php
  $host = 'host';
  $user = 'user';  
  $pass = 'pass';
  $db = 'db';
  try {
    $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO users (username, password, email) VALUES ('Johny', 'Dawkins', 'johny@example.com')";	
    // use exec() because no results are returned
    $conn->exec($sql);
    $latest_id = $conn->lastInsertId();
    echo "Insert successful. Latest ID is: " . $latest_id;
  } catch(PDOException $e) { 
    echo $sql . "<br>" . $e->getMessage(); 
  }
  $conn = null; 
?>

MySQL Last Insert ID: Summary

  • Using MySQL and PHP, it is easy to fetch the ID of the last entry you inserted.
  • Thanks to this function, you can always know how many records you have inserted.
  • If you are using MySQLi procedural connection, the easiest way to get the ID of the last entry is calling mysql_insert_id() statement.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()