We have seen SQL SELECT order to get information from MySQLi table. At the point when you select lines, the MySQLi worker is allowed to restore them in any request, except if you teach it in any case by saying how to sort the outcome. In any case, you sort an outcome set by adding an ORDER BY condition that names the segment or sections you need to sort by.
Syntax
Here is nonexclusive SQL sentence structure of SELECT order alongside ORDER BY proviso to sort information from MySQL table −
SELECT field1, field2,...fieldN table_name1, table_name2...
ORDER BY field1, [field2...] [ASC [DESC]]
You can sort returned result on any field gave that recorded is being drilled down.
- You can sort result on more than one field.
- You can utilize catchphrase ASC or DESC to get bring about rising or plummeting request. Of course, it's rising request.
- You can utilize WHERE...LIKE proviso in common manner to put condition.
Using ORDER BY clause at Command Prompt
This will utilize SQL SELECT order with ORDER BY proviso to bring information from MySQLi table tutorials_inf.
Example
Evaluate the accompanying model, which returns bring about plunging request.
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_inf ORDER BY id desc;
+----+-------+
| id | name |
+----+-------+
| 4 | ram |
| 3 | raghu |
| 2 | johar |
| 1 | sai |
+----+-------+
4 rows in set (0.00 sec)
mysql>
Check all id's are drilled down in sliding request.
Using ORDER BY clause inside PHP Script
You can utilize comparable punctuation of ORDER BY proviso into PHP work mysqli_query(). This capacity is utilized to execute SQL order and later another PHP work mysqli_fetch_array() can be utilized to get all the chose information.
Example
Evaluate the accompanying model, which returns bring about slipping request of instructional exercise creator.
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'TUTORIALS';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully</br>';
$sql = 'SELECT * from tutorials_inf ORDER BY id desc';
if($result = mysqli_query($conn, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>name</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
The example yield ought to be this way −
Connected successfully
id name
4 ram
3 raghu
2 johar
1 sai