2013-02-06 178 views
1

這裏有非常similar questions,但經過大量的搜索和嘗試不同的事情後,我仍然卡住了。mysqli_fetch_assoc返回重複數據

當使用mysqli_fetch_assoc()填充數組時,每行都被添加兩次。

$query = "SELECT column FROM table WHERE year = 2012"; 
if ($result = mysqli_query($connect, $query)) { 
    while ($row = mysqli_fetch_assoc($result)) { 
    $data[] = $row["column"]; 
    } 
echo implode(',', $data); 
mysqli_free_result($result); 
} 

這是返回以下: 1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10

我期待1,2,3,4,5,6,7,8,9,10

我添加了一些額外的線路做一些調試...

print_r($data)產量

Array ( 
[0] => 1 
[1] => 2 
[2] => 3 
[3] => 4 
[4] => 5 
[5] => 6 
[6] => 7 
[7] => 8 
[8] => 9 
[9] => 10 
[10] => 1 
[11] => 2 
[12] => 3 
[13] => 4 
[14] => 5 
[15] => 6 
[16] => 7 
[17] => 8 
[18] => 9 
[19] => 10) 

print_r($result);產量

mysqli_result Object 
( 
[current_field] => 0 
[field_count] => 1 
[lengths] => 
[num_rows] => 10 
[type] => 0 
) 

如果[num_rows] => 10,我使用mysqli_fetch_assoc(),而不是mysqli_fetch_array(),爲什麼它添加值到陣列的兩倍?

+0

我不是一位有經驗的PHP開發人員 - 但是現在不應該使用PDO嗎? –

+2

@JonClements更新了標題。他正在使用mysqli,而不是mysql_ * – Mike

+1

MySQLi是PDO的合適替代品。 –

回答

3

也許你已經將一些數據分配給了$data數組。嘗試之前while指令,清空:

$query = "SELECT column FROM table WHERE year = 2012"; 
if ($result = mysqli_query($connect, $query)) { 
    $data = array(); 
    while ($row = mysqli_fetch_assoc($result)) { 
    $data[] = $row["column"]; 
    } 
echo implode(',', $data); 
mysqli_free_result($result); 
} 

,看看它輸出。

我相信column不是一個真正的專欄名稱,否則你會得到一個錯誤。

+0

你是對的;增加'$ data = array()'修復它。謝謝你的幫助。 –

+0

+1,因爲它值得 – 2013-02-06 20:25:05