HOW TO FETCH SORTED/ORDERED DATA FROM MYSQL USING PHP - CULT CODE
In this tutorial, we will learn how to fetch sorted data from MYSQL using PHP with ORDER conditions.
1. Create a table name user.
Use the code below to create a table:
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(251) NOT NULL,
`email` varchar(251) NOT NULL,
`password` varchar(251) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Now create a file connect.php:
This file will help us to connect PHP to Mysql.
<?php
$connect = mysqli_connect("localhost", "root", "password", "demo");
?>
3. Now create a file index.php:
Paste the below code in your index.php file. In this code, we will fetch data ordered by ASC name (A to Z) Ascending form.
<?php
include('connect.php');
$data_query = "SELECT * FROM user ORDER BY NAME ASC";
$data_result = mysqli_query($connect, $data_query);
if(mysqli_num_rows($data_result) > 0)
{
while($row = mysqli_fetch_array($data_result))
{
?>
Name: <?php echo $row['name']; ?><br>
Email: <?php echo $row['email']; ?><br><br>
<?php
}
}
?>
4. Run your project:
Tips:
There are several order forms used in MySql to Sort data. Examples are the following below.
- ORDER BY name ASC (A to Z)
- ORDER BY name DESC (Z to A)
- ORDER BY id ASC (1 to 9)
- ORDER by id DESC (9 to 1)



Comments
Post a Comment