Easy learning with example program codes

PHP MySQLi Order By

The PHP Order By statement is used to fetch data in an increasing or decreasing order on the basis of column.

To select data in an increasing order.


SELECT * FROM table_name order by column_name

To select data in a decreasing order.


SELECT * FROM table_name order by column_name desc

PHP mysqli_connect() function:

PHP mysqli_connect() function is used to open a new connection to the MySQL server. If the connection is established this function returns the resource, else it returns a null.

PHP mysqli_query() function:

PHP mysqli_query() function is used to perform a query against the MySQL database.



Connection: This is a required parameter which is used to specify the MySQL connection to use.

Query: This is an optional parameter which is used to specify the query string.

Resultmode: This is an optional parameter which is used to specify a constant either MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT.

MYSQLI_STORE_RESULT is the default value of the resultmode. MYSQLI_USE_RESULT is used when a large amount of data need to be retrieved.

PHP mysqli_num_rows(mysqli_result $result):

The PHP mysqli_num_rows(mysqli_result $result) is used to retrieve number of rows in a table.

PHP mysqli_fetch_assoc(mysqli_result $result):

The PHP mysqli_fetch_assoc(mysqli_result $result) is used to retrieve rows of a table as an associative array. The column name of the table are the key of the array. As the number of rows ends, PHP mysqli_fetch_assoc(mysqli_result $result) function returns a NULL value in the array.


<!DOCTYPE html>
$phpconnect = mysqli_connect("localhost","Ben","Ben_password");
if (mysqli_connect_errno())
echo "Connection Failed; " . mysqli_connect_error();
$phpdatabase = "SELECT * FROM MyFriends order by firstname";
$result = mysqli_query($phpconnect, $phpdatabase);
if ($result->num_rows > 0)
while($row = $result->fetch_assoc()) 
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]." - Mail_ID: " . $row["email"]. "<br>";
	echo "No results";


id: 1 - Name: BEN DICHOSTA - Mail_ID:
id: 3 - Name: FLAIRA GATES - Mail_ID:
id: 2 - Name: JOHN DEY - Mail_ID:
Please follow and like us:
Posted in PHP   

Copyright © 2020 CodesJava Protection Status