PHP MySQL Order By


Prev Tutorial Next Tutorial

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.

mysql_query() is used to excecte selected query. In below example variable sql is passed inside mysql_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 = mysql_connect($server, $user, $pass)
or die("Could not connect to server ... \n" . mysql_error ());

// select database
mysql_select_db($db)
or die("Could not connect to database ... \n" . mysql_error ());

?>

create-table.php

Create Table in database

<?php

include 'connect-db.php';

$sql = "SELECT * FROM  letter_dispatch ORDER BY  user_id DESC";  
$result = mysql_query($sql, $connection);

?>

<table>
<tr><th>user_id</th><th>First Name</th><th>Last Name</th></tr>

<?php

if ($result)
 {
  while($row = mysql_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>

mysql_close($conn);

?>

Output


Prev Tutorial Next Tutorial

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain, Tutorialday.com, SeosmoTools.com @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: hitesh.xc@gmail.com WhatsApp no. 8882538826

Yahoo Advertisements