PHP- get the last 4 ids inserted in the database

0

I have a database where 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 primary key is autoincriment.

When doing the Sql query, when using "Limit 4" is enough to fetch the last 4, or not? Or do I make the process easier if I create a datetime column inside the table, where whenever a new item is inserted it stores the date and time it was entered?

Q: I'm using MySql database

    
asked by anonymous 20.09.2016 / 23:20

2 answers

5

I think the code you're looking for is:

SELECT id FROM Products ORDER BY id DESC LIMIT 4;

In addition to LIMIT 4 you need to sort by descending order so that you search for the last 4, not the first 4.

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

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

    
20.09.2016 / 23:25
0

I usually use:

 order by tabela.id_da_tabela desc limit 4
    
20.09.2016 / 23:27