0

I need some help sorting my score value's of my sql database

    <table border = '2'>
    <?php

    $con = mysql_connect("localhost", "root", "");
    if(!$con)
    {
        echo "Could not establish connection to the database " . mysql_error();
    }

    $mydb = mysql_select_db("users", $con);
    if (!$mydb)
    {
        echo "Error selecting database " . mysql_error();
    }

    $mystatement = mysql_query("SELECT * FROM people");
    $dbcount = mysql_num_rows($mystatement);
    $selection = array(0 => "");
    $nameselection = array(0 => "");

    $i = 0; 
        while ($row = mysql_fetch_array($mystatement))
        {
        $selection[$i] = $row['score'];
        $nameselection[$i] = $row['username']; 
        //echo "<tr> <td>$row[username]</td> <td>$row[score]</td></tr>";
        $i++; 
        }
arsort($selection);
ksort($nameselection);

for ($x = 0; $x < $dbcount; $x++)
{
    echo "<tr> <td>$nameselection[$x]</td> <td>$selection[$x]</td> </tr>"; 
}


    ?>

    </table>

im trying to post the user's scores from my game to a table, sorting them from highest to lowest. I'm just stuck..

4 Answers 4

4

Change

$mystatement = mysql_query("SELECT * FROM people");

To

$mystatement = mysql_query("SELECT * FROM people ORDER BY score DESC");

Remove the array sort

arsort($selection);
ksort($nameselection);
Sign up to request clarification or add additional context in comments.

2 Comments

beautiful, i'm new to sql, didn't even know you could do that. thank you VERY much
A tutorial can be useful.
2
$mystatement = mysql_query("SELECT * FROM people ORDER BY score DESC");

1 Comment

+1 even though you were third to answer, you were first to include the correct fieldname, score
2

Use ORDER BY in SQL query like this:

SELECT * FROM people ORDER BY score DESC

Comments

1

You can sort them DB-side using "Order by"

ie. SELECT * FROM people ORDER BY scores desc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.