Reputation: 36632
How can I display only the LAST 10 results from a mysql query?
I want anything prior to the last 10 results to be ignored when the results are output.
<?php
$query = mysql_query("SELECT * FROM graphs WHERE sid=2 ORDER BY id");
while($info = mysql_fetch_array($query)){
$graph_id = $info['id'];
$graph_info = $info['labels'];
$graph_fig = $info['figures'];
echo "<label>" . $graph_info .":<span style='background-color: #06F;'>" . $graph_fig . "</span></label>";
}
?>
EDIT I forgot to mention that the results must be displayed in ASCENDING order sorted by the id column.
Upvotes: 5
Views: 11796
Reputation: 14549
SELECT * FROM (SELECT * FROM graphs WHERE sid=2 ORDER BY id DESC LIMIT 10) g ORDER BY g.id
Fetching last 10 records but resultset still in asc order.
Upvotes: 15
Reputation: 50966
ORDER BY id DESC LIMIT 10
at the end of your query. It will order your ids descending and therefore the first result will be the newest
Upvotes: 3
Reputation: 39055
SELECT * FROM graphs WHERE sid=2 ORDER BY id DESC LIMIT 10;
Explanation: by default results in an ORDER BY are sorted by ascending (ORDER BY ASC). By specifying descending (DESC) they are sorted in reverse order, the LIMIT 10 then takes the top 10 results.
Upvotes: 4