user1072014
user1072014

Reputation: 37

Sorting database data with php

Newbie here. I am having some trouble with PHP some code. I currently have 1 database, consisting of two tables. The two tables are labeled as members and member_stats. The members table consists of 3 columns (Fname, Lname, MemberID), the member_stats table consists of 11 columns (user_name, first_name, last_name, avatar, num_friends, num_checkins, total_cards, total_selfmade_cards, total_followings, total_photos).

I am fetching the data from my database with

$result = mysqli_query($con,"SELECT * FROM member_stats ");

I am then displaying the data into html table on the page with the following code.

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><div class='user_nav_btn open' ><img src='" . $row[avatar] . "' alt='' /></div></td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['MemberID'] . "</td>";
echo "<td>" . $row['num_friends'] . "</td>";
echo "<td>" . $row['total_cards'] . "</td>";
echo "<td>" . $row['num_checkins'] . "</td>";
echo "<td>" . $row['total_selfmade_cards'] . "</td>";
echo "<td>" . $row['total_followings'] . "</td>";
echo "<td>" . $row['total_photos'] . "</td>";
echo "</tr>";
}

I am trying to get the table to print all the rows of data based on the value of total_cards in order from highest to lowest. No matter what I have tried, I haven’t been able to get it to work. I have only been met with errors on everything I have tried. Any suggestions? I have looked over http://php.net/manual/en/array.sorting.php several times with no luck.

Upvotes: 1

Views: 92

Answers (2)

user8556290
user8556290

Reputation:

As the firt comment drive you on the good way, you don't need PHP sorting as you did, just a Query SQL is sufficient.

SELECT * FROM member_stats ORDER BY total_cards ASC

By default a SELECT is ASC, i just added for knowing he can do (ASC | DESC) sorting in the Query.

Upvotes: 1

sam
sam

Reputation: 2984

The simplest method would be for you to update your SQL; you can order your server requests the results.

$sql = "SELECT * FROM member_stats ORDER BY total_cards";

You also have the ASC (ascending) or DESC (descending) keywords which will determine the order from ascending to descending.

This will query your database to get the data in the order of total_cards

You can also get all of the results in an array, and then sort it using some Javascript table library, and manipulate it that way.

Upvotes: 2

Related Questions