mysqli fetch array displays only the first row

匿名 (未验证) 提交于 2019-12-03 01:14:02

问题:


I have written this code:

require("config.php");  $rows = array();  $query = "SELECT accountname, bill_city, bill_code, bill_country,  bill_street, latitude, longitude, setype FROM vtiger_accountbillads, vtiger_account, vtiger_geocoding WHERE accountaddressid = accountid AND accountid = crmid";  $result = mysqli_query($connection, $query);  $rows_number = $result->num_rows; echo $rows_number . "

"; $row = mysqli_fetch_array($result); if($result->num_rows > 0){ for($i=0; $i $row[0], "city" => $row[1], "code" => $row[2], "country" => $row[3], "street" => $row[4], "latitude" => $row[5], "longitude" => $row[6], "type" => $row[7]); } } $json = json_encode($rows); print $json; mysqli_free_result($row); mysqli_close($connection);

I'm trying to fetch several data using the query written in the code above, but it displays the first row 47 times. Why? What am I doing wrong? Thanks!

回答1:

You need to iterate through the result set returned by MySQL. That means calling mysqli_fetch_array() for each row of that result set. You can do that using a while loop:

while($row = mysqli_fetch_assoc($result)) {     $rows[] = array("name"      => $row['name'],                     "city"      => $row['bill_city'],                     "code"      => $row['bill_code'],                     "country"   => $row['bill_country'],                     "street"    => $row['bill_street'],                     "latitude"  => $row['latitude'],                     "longitude" => $row['longitude'],                     "type"      => $row['setype']);     } } 


回答2:

Don't use for loop for fetching SQL queries. Use while instead:

if($result->num_rows > 0){     while($row = mysqli_fetch_assoc($result))     {         $rows[] = array("name" => $row[0],                         "city" => $row[1],                         "code" => $row[2],                         "country" => $row[3],                         "street" => $row[4],                         "latitude" => $row[5],                         "longitude" => $row[6],                         "type" => $row[7]);     } } 


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