PHP-get the last 4 id’s inserted in the database

Asked

Viewed 51 times

0

I have a database in which one of the tables has the designation "Products" and I would like to extract from it the last 4 items inserted in it. The column with the main key (Primary key) is autoincriment.

When doing the Sql query, using "Limit 4" is enough to fetch the last 4, or not? Or does it make the process easier to create within the table a column of type datetime, in which whenever a new item is inserted this saves the date and time when it was inserted?

P.S.: I am using Mysql database

  • You want to know the last 4 records recorded by any system user, or you want to know the last 4 records entered in a single INSERT?

2 answers

5


I believe the code you’re looking for is:

SELECT id FROM Products ORDER BY id DESC LIMIT 4;

Beyond the LIMIT 4 you must order in descending order, so that you look for the last 4 and not the first 4.

The column with the date it was added may be useful, but I don’t know if it would be so useful if your only use is to sort, since you already have a primary key, but could be used for other purposes.

Remember that the attribute LIMIT 4 should be used after the ORDER BY, otherwise, it will limit to 4 records (either the first or the last) before sorting the records. Therefore, use the LIMIT 4 at the end of query.

  • Thank you so much!!! I completely forgot the order by!!!

0

Normally use:

 order by tabela.id_da_tabela desc limit 4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.