Sean Davidson Sean Davidson - 7 months ago 9
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:

$i=0;
while ($i < $nnum)
{
// take each row from the array $nresult
$i++;
}


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

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'];
    // ...
}