get_result() - > fetch_assoc()总是返回1行

时间:2016-01-30 15:37:46

标签: php mysqli

我有这个PHP代码:

public function getcabang(){

    $cabang = $this->conn->prepare("SELECT nama_cabang,alamat FROM cabang");

    if ($cabang->execute()){
        $cbg = $cabang->get_result()->fetch_assoc();
        $cabang->close();
        return $cbg;
    } else {
        return NULL;
    }
}

但它总是返回1行:

{"error":false,"cabang":{"nama_cabang":"Senayan","alamat":"Pintu 1 Senayan"}}

即使表格中有超过1行

1 个答案:

答案 0 :(得分:1)

你需要迭代才能得到每一行,这里是php.net的一个例子:

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->free();
}

在你的情况下,那将是:

public function getcabang(){

    $cabang = $this->conn->prepare("SELECT nama_cabang,alamat FROM cabang");

    if ($cabang->execute()){
        $cbg = array();
        $result = $cabang->get_result();
        while($row = $result->fetch_assoc()) {
            $cbg[] = $row;
        }
        $cabang->close();
        return $cbg;
    } else {
        return NULL;
    } 
}

另外,更好的解决方案是使用mysqli_fetch_all(仅适用于mysqlnd)