How Can I Sort Records Order By Using Mysqli and PDO?

The ORDER BY clause is used with the SELECT statement. Here the records of the table are sorted by the column ascending (ASC) and descending (DESC) order.

Note: If ASC or DESC keyword is not used then ASC default is set.

SELECT column_name(s) FROM table_name
ORDER BY column_name(s) ASC|DESC

Example for Sorting Records with ORDER BY clause using MySQLi

<?php
$conn = mysqli_connect("localhost", "root", "", "expertstutorials");
if($conn){
echo "Connected successfully.<br />";
}
else{
echo "Connection failed : ".mysqli_connect_error();
}
$select = "SELECT * FROM course ORDER BY id ASC";
$result = mysqli_query($conn, $select);
echo "<table>
<tr>
<th>id</th>
<th>Course Name</th>
<th>Course Year</th>
</tr>";
if(mysqli_num_rows($result) > 0){
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>
<td>".$rows['id']."</td>
<td>".$rows['course_name']."</td>
<td>".$rows['course_year']."</td>
</tr>";
}
echo "</table>";
}
else{
echo "rows not found in table";
}
mysqli_close($conn);
?>

Example for Sorting Records with ORDER BY clause using PDO

<?php
$server = "localhost";
$user = "root";
$password = "";
$db = "expertstutorials";
try{
$conn = new PDO("mysql:host=$server;dbname=$db", $user, $password);
echo "Connected successfully.";
$select = "SELECT * FROM course ORDER BY id ASC";
$result = $conn->query($select);
echo "<table>
<tr>
<th>id</th>
<th>Course Name</th>
<th>Course Year</th>
</tr>";
if($result->rowCount() > 0){
while($rows = $result->fetch()){
echo "<tr>
<td>".$rows['id']."</td>
<td>".$rows['course_name']."</td>
<td>".$rows['course_year']."</td>
</tr>";
}
echo "</table>"; 
}
else{
echo "rows not found in table";
}
} 
catch(PDOException $e){
echo "Table Creation failed : " . $e->getMessage();
}
$conn = null;
?>
Cialis (Tadalafil) är den främsta konkurrenten till Viagra (Sildenafil) på marknaden för erektil dysfunktion. köpa Cialis i Sverige föredras av många på grund av sin längre varaktighet och anses vara det mest kostnadseffektiva varumärkesbaserade ED-läkemedlet som finns tillgängligt i Sverige. Cialis finns i två varianter: Cialis och Cialis Daily, och fyra olika doseringar: 2,5 mg, 5 mg, 10 mg och 20 mg, erbjuder Cialis också en rad olika alternativ för att passa patientens behov.