get_result()->fetch_assoc() always returning 1 row

点点圈 提交于 2020-02-25 13:21:09

问题


I have this php code :

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;
    }
}

but it always returning 1 row :

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

even though it have more than 1 row in table


回答1:


You need to iterate to get every row, here is an example from 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();
}

In your case, that would be :

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;
    } 
}

Also, a better solution could be to use mysqli_fetch_all (Available only with mysqlnd)



来源:https://stackoverflow.com/questions/35103594/get-result-fetch-assoc-always-returning-1-row

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