Defain Defain - 1 year ago 96
PHP Question

How to sort a table from SQL using variable in PHP

I have a problem in sorting table from information took from SQL database. I need to sort the table with PHP variable $points (which is count from two different fields in SQL database and printed as last part of the table so the points IS NOT included in SQL).

So basically I need to sort the table by $points without saving any information about points directly to the SQL database.

I wonder what would be the simplest way to do it if it is possible?

And the PHP code is down here:

if(isset($_REQUEST['button'])) {
$connect = mysqli_connect("localhost","root","","Points_database");
if (mysqli_connect_errno()) {
echo "Error: ", mysqli_connect_error();
$sql = "SELECT * FROM Points_table;";
$query = mysqli_query($connect,$sql);
echo "<table><tr><td>Team</td><td>Games</td><td>Wins</td><td>Tie</td><td>Losses</td><td>Goals</td><td>Points</td></tr>";
while($row = mysqli_fetch_array($query,MYSQL_ASSOC)) {
$points= $row['wins'] * 3 + $row['tie'];
if($rowcount%2==0) {
echo "<tr class='rowstyle2'>";
else {
echo "<tr>";
echo "<td>".$row['team']."</td><td>".$row['games']."</td><td>".$row['wins']."</td><td>".$row['tie']."</td><td>".$row['losses']."</td><td>".$row['goals']."</td><td>".$points."</td></tr>";
echo "</table>";

Answer Source

why not?

SELECT *, (wins*3 + tie) AS pts FROM table ORDER BY pts DESC

or if you dont want calculations in SQL

SELECT * FROM table ORDER BY wins*3 + tie DESC

here it is:!2/d2045/4

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download