1

Please help me learn what is wrong with this PHP / MySQL query.

This is my channels table:

name    url              id      key
BBC2    http://url.com/2 BBC2   2
BBC1    http://url.com/1 BBC1   1

This works:

$getchans = "SELECT * FROM channels";  
$channels = mysqli_query($db,$getchans);    
foreach ($channels as $channel)
{
    // do stuff 
}

This does not work:

$getchans = "SELECT * FROM channels ORDER BY key ASC";  
$channels = mysqli_query($db,$getchans);    
foreach ($channels as $channel)
{
    // do stuff 
}

and gives error Warning: Invalid argument supplied for foreach()

Can anyone please tell me why it doesn't work when MySQL query/result is ordered?

Thank you.

JustCarty
  • 3,839
  • 5
  • 31
  • 51
Paul
  • 38
  • 6

3 Answers3

2

esacepe Key Keyword, refer

$getchans="SELECT * FROM channels ORDER BY `key` ASC";  
Community
  • 1
  • 1
Anil
  • 3,722
  • 2
  • 24
  • 49
0

key is a keyword in mysql so you need to use `` quotes in your query.

$getchans="SELECT * FROM channels ORDER BY key ASC";

0

Your query failed because key is a reserved keyword in SQL. Try to change the name of the column key to something else. There is also a very usefull list with all the reseverd keywords.

If you don't prefer an other name for this column, you can try to escape it by using the following query:

SELECT * FROM channels ORDER BY `key` ASC

List with reserved keywords can be found on https://dev.mysql.com/doc/refman/5.7/en/keywords.html

Goodluck!

node_modules
  • 4,790
  • 6
  • 21
  • 37
  • Thanks for the information. Unfortunately now it is not ordering correctly but I found a fix, adding +0 to the query field. SELECT * FROM channels1 ORDER BY 'keyid+0' ASC; – Paul Mar 31 '17 at 09:11