tags:

views:

39

answers:

2
$data = mysql_query("SELECT * FROM phpbb_posts ORDER BY post_id DESC LIMIT 4")
or die(mysql_error());

Above is my code and I'm having problems with the Limit part.
When I first set it, everything seems perfect, but I could come back in a few hours and look at the page again and a different number of records could be shown, even though the code is exactly the same.

Any ideas how I can fix that?

+3  A: 

The data is different because more posts are made since you last checked the page. You're ordering by post_id, where the highest value will be the most recent post.

The easiest way keep the previous records is to cache the data - store it. But then the cache needs to know when to refresh that cache - otherwise it will never change.

If there's a date/time column, you could use that to filter the results before the LIMIT is applied. But it'd have to be wide enough to get at least four records. And the same problem with the dates to look at - at some point, you want those dates to change or the data served by the page will never change.

OMG Ponies
doesn't LIMIT in MySQL always refer to the # of records returned? why would the sort matter except to determine which records are returned, not the number?
Tahbaza
@Tahbaza: `LIMIT` is irrelevant to the question - the issue is constantly changing data. The LIMIT could be 4, 10, 100 etc and the issue would still be the same - every page refresh, the first row is not the same as before (unless no one is creating posts).
OMG Ponies
It doesn't matter what order he's specifying, the resultset will always have 4 rows. The problem must be a few lines below (assuming OP is getting 5, 6, 3, 8 results instead of 4).
Ben
@Ben: The order in the query is `post_id` - unless there's less than four records in that table, it's unlikely to show less than four rows. Likewise as you adjust the LIMIT clause...
OMG Ponies
@OMG: You may be right, it's unclear from the question, but from my reading he says "number of records" which means the content of the questions returned is irrelevant and the # returned is.
Tahbaza
A: 

You don't specify how many records being returned are concerning you. The LIMIT should return a MAX of 4 records, fewer if there were not at least 4 that would be returned by your query. If you ever have MORE than 4 records returned then you have a problem.

Tahbaza