2016-01-30 67 views
0

我有這樣的PHP代碼:get_result() - > FETCH_ASSOC()總是返回1行

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

'FETCH_ASSOC()'一次只返回一行。您需要迭代結果集以獲取所有行。 – jbafford

回答

0

您需要遍歷獲得每一行,這裏是從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)