Deprecated: implode(): Passing glue string after array is deprecated. Swap the parameters in /home/ct33h8azxpia/public_html/wp-content/themes/aquarella-lite/single.php on line 94
How Can I Sort Records Order By Using Mysqli and PDO? - Experts PHP

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;
?>