mysqli fetch数组仅显示第一行

时间:2014-05-05 13:15:57

标签: php mysqli


我写了这段代码:

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 . "<br/><br/>";

$row = mysqli_fetch_array($result);

if($result->num_rows > 0){
    for($i=0; $i < $rows_number; $i++) {
            $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]);
    }
}

$json = json_encode($rows);
print $json;

mysqli_free_result($row);
mysqli_close($connection);

我正在尝试使用上面代码中编写的查询来获取多个数据,但它显示第一行47次。为什么?我究竟做错了什么?谢谢!

2 个答案:

答案 0 :(得分:2)

您需要遍历MySQL返回的结果集。这意味着为该结果集的每一行调用mysqli_fetch_array()。您可以使用while循环来执行此操作:

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']);
    }
}

答案 1 :(得分:2)

不要使用loop来获取SQL查询。请改用while

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]);
    }
}
相关问题