mysql_fetch_array return only one row

笑着哭i 提交于 2019-12-17 03:21:15

问题


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.

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?

Thanks for the help.


回答1:


That's because the array represents a single row in the returned result set. You need to execute the mysql_fetch_array() function again to get the next record. Example:

while($data = mysql_fetch_array($array)) {
  //will output all data on each loop.
  var_dump($data);
}



回答2:


You should be using while to get all data.

$array_result = array();
while ($row = mysql_fetch_array($array, MYSQL_NUM)) {
    $array_result[] = $row;
}
echo $array_result[4];



回答3:


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 :)



来源:https://stackoverflow.com/questions/7001320/mysql-fetch-array-return-only-one-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!