Member-only story

How to get the last record in MySQL using PHP

Bipsmedium
2 min readSep 19, 2021

--

Hi friends, in this tutorial we will learn how to get the last record in MySQL using PHP. This is very useful and almost required in any kind of web application while creating a dynamic website or any customized software.

Actually, there are two ways by which we can get the last inserted record from the MySQL database with the help of a MySQL query inside a PHP script and display the desired results.

Also read, PHP code to retrieve data from MySQL database and display

The ways to get the last record in MySQL using PHP

  • order by
  • timestamp i.e. created at

The order by method to fetch the data from the MySQL database

By using the order by method, you can first sort the data in descending order according to the primary key ‘id’ and then putting the LIMIT 1 i.e. we need only the last inserted record. If you do not put LIMIT 1 then it will fetch all records in descending order.

Query:-

SELECT * FROM employee_info ORDER BY id DESC LIMIT 1

Example:- In order to explain the example, I am using a table employee_info from my database as shown below

How to get last record in MySQL using PHP

--

--

Bipsmedium
Bipsmedium

Written by Bipsmedium

Hi, This is Biplab and I am a PHP laravel developer and other open source technologies. I am here to share my experience with the community.

No responses yet