Sort data during read from SQL using PHP

by | Jun 22, 2021 | PHP

Home » PHP » Sort data during read from SQL using PHP

Introduction

Whatever we see on our website, it is either saved within HTML or being fetched from a table. The HTML has a script file attached with it which calls backend, where SQL codes are written. These SQL codes interact with database. In this article we will learn how to sort data during read from SQL using PHP.

Syntax

SELECT * FROM <table name> WHERE <field name> = '{<local variable>}' ORDER BY <required field name> ASC|DESC

How to sort data during read from SQL using PHP

In the below query, we pass the query via connection and get the response in a variable called $result. If the result variable is not empty then we echo (i.e. send back to frontend) the data, else we return a message “No Data”.

To sort data based upon a particular column, we need to pass that column name followed by ASC|DESC (Ascending or Descending).

// Perform query
if ($result = $conn -> query("SELECT * FROM transactions WHERE ReceivedDate = '{$date}' ORDER BY timestamp DESC")) {
    if($result->num_rows > 0) {
    $i = 0;
    while($row = $result->fetch_assoc()){
    $dataArray[$i] = $row;
    $i = $i + 1;
}
    echo json_encode($dataArray);
}
}
else{
$dataArray[0] = 'No data';
echo json_encode($dataArray);
}

You can check all the steps involved in read operation via PHP here.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author