How to fetch n latest numbers of record from a MySQL table using PHP in an ascending or descending order?
If you are new on PHP and MYSQL and wondering how to fetch just n numbers of records from a database table and group them by ascending or descending order, then you are at right place.
Lets suppose a database table as below:
Database name : “comments”
Table name : “comments”
Fields
Lets suppose a database table as below:
Database name : “comments”
Table name : “comments”
Fields
- id (Auto-increment)
- name (varchar 100)
- comment (varchar 100)
Mysql statement to fetch 5 latest records and sort by descending order
SELECT * FROM comments ORDER BY id DESC LIMIT 5
Full Php Code:
<?php $hostname="localhost"; $username="root"; $password="root"; $conn=mysql_connect("$hostname","$username","$password"); mysql_select_db("comments"); //default password for mamp is "root" and for xampp is empty $find_database = mysql_query("SELECT * FROM comments ORDER BY id DESC LIMIT 5"); if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; } else { while($row = mysql_fetch_assoc($find_database)) { $name=$row['name']; $comment=$row['comment']; echo'<font size="4" color="purple"> <b>'.$name.'</b>:'.$comment.'</font><hr></div>'; } } ?>
It has been assumed that your table has auto-increment field “id” .
Comments
Post a Comment