How to get last record in MySQL using PHP

Bipsmedium
2 min readSep 19, 2021
How to get last record in MySQL using PHP

Hi friends, in this tutorial we will learn how to get 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

PHP Code:-

Result:-

How to get last record in MySQL using PHP

Timestamp to get the last inserted record in PHP

In this case, you need to sort the data in descending order first according to the primary key ‘id’, and then LIMIT 1 should be added in the query. LIMIT 1 will be applicable in both cases.

Query:-

SELECT * FROM employee_info ORDER BY created_at DESC LIMIT 1

The example is the same as the above example except for the select query.

PHP Code:-

CONCLUSION:- I hope this article will help you to understand the concept. If you have any doubt then please leave your comment below.

--

--

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.