2013-07-29 195 views
1

我正在從mysql遷移到mysqli,並且我無法從查詢中返回數據庫中的多行。mysqli查詢只返回第一行

$db = new mysqli($hostname, $sql_us, $sql_us_pwd, $sql_db); // This is already connected 

function db_query($db, $query, $type = 'object') { 

    global $db; 

    $result = $db->query($query); 

    if ($type == 'assoc') { 
     while($row = $result->fetch_assoc()) { 
      return $row; 
     } 
    } else {  
     while($row = $result->fetch_object()) { 
      return $row; 
     } 
    } 

    mysqli_free_result($result); 

} 



$query = "SELECT * FROM `users`"; 
$user = db_query($db, $query); 
print_r($user); // This is only returning the first row of results 

我顯然試圖使一個功能,我可以查詢數據庫,要麼在關聯數組或者對象返回結果。我究竟做錯了什麼?

+1

http://php.net/manual/en/function.return.php –

+1

這樣的功能有支持**預處理語句**或有沒有用它在所有。 –

回答

2

使用此代碼:

$rows = array(); 
if ($type == 'assoc') { 
    while($row = $result->fetch_assoc()) { 
     $rows[] = $row; 
    } 
} else {  
    while($row = $result->fetch_object()) { 
     $rows[] = $row; 
    } 
} 
return $rows; 

您正在使用的,而和返回內返回結束第一次迭代這就是爲什麼你得到只有一排後while循環。

1

您只返回第一行。你必須返回一個數組。

1
$arr = array(); 
if ($type == 'assoc') { 
    while($row = $result->fetch_assoc()) { 
    $arr[] = $row; 
    } 
} 
else {  
    while($row = $result->fetch_object()) { 
    $arr[] = $row; 
    } 
} 
return $arr; 
2

您需要存儲while循環值放入數組試試這個

$rows = array(); 
if ($type == 'assoc') { 
    while($row = $result->fetch_assoc()) { 
     $rows[] = $row; 
    } 
} else {  
    while($row = $result->fetch_object()) { 
     $rows[] = $row; 
    } 
} 
return $rows; 
2

當你在一個函數返回它停止在這一點上執行,並返回到它被稱爲從與價值你正在返回。

在你的情況下,當你做一個返回$行時,只要第一行被讀取,你就會退出函數。

修復是:

$result = array(); 
if ($type == 'assoc') { 
    while($row = $result->fetch_assoc()) { 
     $result[] = $row; 
    } 

} else {  

    while($row = $result->fetch_object()) { 
     $result[] = $row; 
    } 
} 
return $row;