简体   繁体   中英

PHP - How to order data by ascending or descending

I have a form that allows a user to retrieve information from a database.

Currently users are able to retrieve the information from the database with the code I have provided (probably terrible coding but it works).

Now I would like the data to display in an asc or dsc order depending on what the user selects on the form. But im not too sure how to go about doing that, any help in the right direction would be much appreciated!

The PHP that retrieves the information:

$sql = "SELECT RunnerID, EventID, Date, FinishTime, Position, CategoryID, AgeGrade, PB FROM Results";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
 echo "<table><tr><th>RunnerID</th><th>EventID</th><th>Date</th><th>FinishTime</th><th>Position</th><th>CategoryID</th><th>AgeGrade</th><th>PB</th></tr>";

 while($row = $result->fetch_assoc()) {
     echo "<tr><td>" . $row["RunnerID"]. "</td><td>" . $row["EventID"]. " </td><td>" . $row["Date"]. " </td><td>" . $row["FinishTime"]. " </td><td>" . $row["Position"]. " </td><td>" . $row["CategoryID"]. " </td><td>" . $row["AgeGrade"]. " </td><td>" . $row["PB"]. " </td></tr>";
 }
 echo "</table>";
} 
else {
 echo "Error";
}

Rather than having PHP do the work, it would be more standard to modify your SQL query to include ORDER BY xxxx ASC or ORDER BY xxxx DESC . If you have a form which you want to allow them to sort by, a decent alternative might be something like:

$userSelectedProperty = $_GET['ThePropertyIWantToSortOn'];
$userSelectedDirection = $_GET['TheDirectionIWantToSortBy'];
$sql = "SELECT RunnerID, EventID ... FROM Results ORDER BY "; // Note the extra space
switch ($userSelectedProperty)
{
    case 'name': { $sql .= "RunnerName"; break; }
    case 'age': { $sql .= "AgeGrade"; break; }
    ...
    default: { $sql .= "RunnerID"; break; } // By default, let's sort by ID
}
if ($userSelectedDirection == 'desc')
{
   $sql .= " DESC"; // Note the preceding space.
}
else
{
   $sql .= " ASC"; // Note the preceding space.
}

This way, the sorting is already done on the database, so you're retrieving the data back in the order you want it already. The reason that I'm using switch statements and if statements even when it looks like it's the same data is that it avoids a vulnerability known as SQL injection . Basically, if you just directly use the variable to build the SQL query, there's nothing stopping some malicious user from providing code that lets them modify the query's intention. For instance, if they passed in something like MyName; DELETE FROM Results; MyName; DELETE FROM Results; as the value for the form input used to generate the field $userSelectedProperty , the resulting $sql string would be something like SELECT RunnerID ... FROM Results ORDER BY MyName; DELETE FROM Results; SELECT RunnerID ... FROM Results ORDER BY MyName; DELETE FROM Results; . Well, that's really bad because to SQL, it's two valid statements. This isn't the best or most comprehensive definition if this is your first time hearing about it, but if you're curious about how to avoid it, I would suggest looking into SQL injection guides.

$fields = array( "RunnerID", "EventID", "Date", "FinishTime", "Position", "CategoryID" );

    $orderby = 0;
    $asc = 0;
    if( isset($_GET['orderby'])) $orderby = (int)$_GET['orderby'];
    if( isset($_GET['asc'])) $asc = (int)$_GET['asc'];

    $sql = "SELECT RunnerID, EventID, Date, FinishTime, Position, CategoryID, AgeGrade, PB FROM Results";

$sql .= " ORDER BY " . $fields[$orderby];
$sql .= " " . $asc ? "ASC" : "DESC";

Rather than having the server do the work, consider having the browser do it instead. Offloading work to the browser is an extremely useful skill, especially with very busy websites.

Put the data into a table without regard for sort order. Then use JavaScript to implement sorting. There are plenty of ways of doing this, for instance:

var tbl = document.getElementById('mytable'),
    trs = tbl.rows, l = trs.length, i, tmp = [];
for( i=0; i<l; i++) tmp.push(trs[i]);
tmp.sort(function(a,b) {
    // compare the rows how you want.
    // return -1 if a comes before b
    // return 1 if b comes before a
    // return 0 if they are equal
});
for( i=0; i<l; i++) tbl.appendChild(tmp[i]);

You can also look into one of the many plug-ins out there on the internet to do this, such as Footable.

Of course, you can always support non-JS users (how outdated are they?) with:

<noscript><a href="?sort=asc">Sort ascending</a></noscript>

When that parameter is present, do the sorting server-side for them, as per the other answers. The overwhelming majority of the time, though, it will be done with JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM