PHP MySQL Order By
Advertisements
Display Record from Database in Decending Order
The order by clause is used to fetch data in ascending order or descending order on the basis of column.
mysqli_query() is used to excecte selected query. In below example variable sql is passed inside mysqli_query(), it means excecute selected query when this function called.
Below query used to select data from user table in ascending order on the basis of user_id column.
Syntax
$sql = "SELECT * FROM letter_dispatch ORDER BY user_id";
Below query used to select data from user table in descending order on the basis of user_id column.
Syntax
$sql = "SELECT * FROM letter_dispatch ORDER BY user_id DESC";
connect-db.php
Connect to database
<?php $server = 'localhost'; $user = 'user_name'; $pass = 'password'; $db = 'database_name'; // Connect to Database $connection = mysqli_connect($server, $user, $pass) or die("Could not connect to server ... \n" . mysqli_error ()); // select database mysqli_select_db($db) or die("Could not connect to database ... \n" . mysqli_error ()); ?>
create-table.php
Create Table in database
<?php include 'connect-db.php'; $sql = "SELECT * FROM letter_dispatch ORDER BY user_id DESC"; $result = mysqli_query($sql, $connection); ?> <table> <tr><th>user_id</th><th>First Name</th><th>Last Name</th></tr> <?php if ($result) { while($row = mysqli_fetch_array($result)) { ?> <tr> <td><?php echo $row["user_id"]; ?></td> <td><?php echo $row["f_name"]; ?></td> <td><?php echo $row["l_name"]; ?></td> </tr> <?php } } ?> </table> mysqli_close($conn); ?>
Output
Google Advertisment