简体   繁体   English

这个MySQL查询和PHP foreach有什么问题

[英]What's wrong with this MySQL query and PHP foreach

Please help me learn what is wrong with this PHP / MySQL query. 请帮助我了解此PHP / MySQL查询出了什么问题。

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() 并给出错误Warning: Invalid argument supplied for foreach()

Can anyone please tell me why it doesn't work when MySQL query/result is ordered? 谁能告诉我为什么订购MySQL查询/结果后它不起作用?

Thank you. 谢谢。

esacepe关键字关键字, 请参阅

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

key is a keyword in mysql so you need to use `` quotes in your query. key是mysql中的关键字,因此您需要在查询中使用``引号。

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

Your query failed because key is a reserved keyword in SQL. 您的查询失败,因为key是SQL中的保留关键字。 Try to change the name of the column key to something else. 尝试将列key的名称更改为其他名称。 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 带有保留关键字的列表可以在https://dev.mysql.com/doc/refman/5.7/en/keywords.html上找到

Goodluck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM