简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM