php mysql_fetch_array 只返回一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7001320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysql_fetch_array return only one row
提问by Ando
Ok, I have the following code:
好的,我有以下代码:
$array = mysql_query("SELECT artist FROM directory WHERE artist LIKE 'a%'
OR artist LIKE 'b%'
OR artist LIKE 'c%'");
$array_result= mysql_fetch_array($array);
Then, when I try to echo the contents, I can only echo $array_result[0];
, which outputs the first item, but if I try to echo $array_result[1];
I get an undefined offset.
然后,当我尝试回显内容时,我只能 echo $array_result[0];
,它输出第一项,但是如果我尝试回显,$array_result[1];
我会得到一个未定义的偏移量。
Yet if I run the above query through PHPMyAdmin it returns a list of 10 items. Why is this not recognized as an array of 10 items, allowing me to echo 0-9?
然而,如果我通过 PHPMyAdmin 运行上述查询,它会返回一个包含 10 个项目的列表。为什么这不被识别为 10 个项目的数组,允许我回显 0-9?
Thanks for the help.
谢谢您的帮助。
回答by Dor
That's because the array represents a single row in the returned result set. You need to execute the mysql_fetch_array()
functionagain to get the next record. Example:
这是因为数组代表返回结果集中的一行。您需要再次执行该mysql_fetch_array()
函数以获取下一条记录。例子:
while($data = mysql_fetch_array($array)) {
//will output all data on each loop.
var_dump($data);
}
回答by veidelis
You should be using while
to get all data.
您应该while
用于获取所有数据。
$array_result = array();
while ($row = mysql_fetch_array($array, MYSQL_NUM)) {
$array_result[] = $row;
}
echo $array_result[4];
回答by CONvid19
I prefer to use this code instead:
我更喜欢使用此代码:
$query = "SELECT artist FROM directory WHERE artist LIKE 'a%'
OR artist LIKE 'b%'
OR artist LIKE 'c%'";
$result = mysql_query($query) or die(mysql_error());
while(list($artist) = mysql_fetch_array($result))
{
echo $artist;
}
If you add more fields to your query just add more variables to list($artist,$field1,$field2, etc...)
I hope it helps :)
如果您在查询中添加更多字段,只需将更多变量添加到列表($artist、$field1、$field2 等...)
我希望它有所帮助:)