Sean Davidson Sean Davidson - 2 years ago 64
PHP Question

SORT BY in MySQL query does not change the order in the query results array

This MySQL query

SELECT * FROM notes WHERE school_code = 'brisch' ORDER BY ID DESC

works in the MySQL terminal (showing records in descending ID order where they held in the table in ascending order) but when I use it in a PHP script as:

$query = "SELECT * FROM notes WHERE school_code = '$skcode' ORDER BY ID DESC";
$nresult = mysql_query($query);
$nnum = mysql_numrows($nresult);

And then output the rows using:

while ($i < $nnum)
// take each row from the array $nresult

It displays the rows in the table order i.e. by ascending ID I thought if they pulled from the table in descending order they would be stored in the array in that same order.

Am I wrong in thinking that?

Answer Source

The error is most likely how you iterate through the results. Replace while loop with mysql_fetch_assoc() and it should work:

while ($row = mysql_fetch_assoc($nresult)) {

    echo $row['id'];
    // ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download