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.
The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.
The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.
The limit keyword is used to limit the number of rows returned in a query result. “SELECT {fieldname(s) | *} FROM tableName(s)” is the SELECT statement containing the fields that we would like to return in our query. “[WHERE condition]” is optional but when supplied, can be used to specify a filter on the result set.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With