2014-10-16 187 views
1

我試圖做一個小的MySQL數據庫的一個非常非常簡單的查詢,使用下面的代碼(在$主機適當的值等):mysqli_fetch_array返回結果只有一個

$connection = mysqli_connect($host, $user_name, $password, $database); 
if (mysqli_connect_errno($connection)) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

$result = mysqli_query($connection, "select university from universities_alpha"); 
$row = mysqli_fetch_array($result); 

echo print_r($result); 
echo '<br><br>'; 
echo print_r($row); 

mysqli_close($connection); 

由於你可以看到,我在一個人類可讀的方式打印出來的結果,得到以下特性:

mysqli_result Object ([current_field] => 0 [field_count] => 1 [lengths] => Array ([0] => 19) [num_rows] => 9 [type] => 0) 1 

Array ([0] => Arizona State Univ. [university] => Arizona State Univ.) 1 

有該列的幾個例子的大學,所以我不知道我在做什麼錯。

+0

閱讀mysqli函數的手冊。你把'fetch_array'放在'while'循環中,因爲它將一行一行地返回,直到它返回null並且循環終止。 – Felk 2014-10-16 23:34:53

回答

4

mysqli_fetch_array每次它被稱爲

時間的工作原理是指針試想以下

$result = mysqli_query($connection, "select university from universities_alpha"); 
$row = mysqli_fetch_array($result); // this is the first row 
$row = mysqli_fetch_array($result); // now it's the second row 
$row = mysqli_fetch_array($result); // third row 

實際顯示的數據,你希望它的方式,我建議你做以下

$rows = array(); 
$result = mysqli_query($connection, "select university from universities_alpha"); 
while($row = mysqli_fetch_array($result)) $rows[] = $row; 
print_r($rows);