1

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?

luchaninov
  • 6,792
  • 6
  • 60
  • 75
Sean
  • 13
  • 3
  • I think we'd need to see the bit inside the curly brackets. – Strawberry Apr 08 '14 at 09:32
  • Also, note that you're using a deprecated api – Strawberry Apr 08 '14 at 09:40
  • Strawberry, thanks for the heads up on the deprecation. Inside the brackets is just something like: $nnotes = mysql_result($nresult,$i,'notes'); $time = mysql_result($nresult,$i,'created'); $usern2 = mysql_result($nresult,$i,'op_code'); $nid = mysql_result($nresult,$i,'id'); etc.... and these fields then get put in their own table and this is repeated for each value of i. will try edvinas.me's solution shortly – Sean Apr 08 '14 at 11:51

2 Answers2

0

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'];
    // ...
}
ek9
  • 3,392
  • 5
  • 23
  • 34
  • Nah, that didn't work either - thanks for the suggestion though. I also tried counting from $nnum to 0 in the WHILE loop - didn't work either! But tried something else I found - answer below... – Sean Apr 09 '14 at 11:07
0

Did this:

$key = "ID";
array_multisort($nresult, SORT_DESC, $key);

got it from:

How to sort an array of associative arrays by value of a given key in PHP?

Community
  • 1
  • 1
Sean
  • 13
  • 3
  • I should add that I still need the 'ORDER BY $key DESC' part in the mysql query. (Though I'm using the deprecated MYSQL api, still - so prob going to be different for MySQLi.) – Sean Apr 10 '14 at 10:06