这里有非常similar questions,但经过大量的搜索和尝试不同的事情,我仍然被卡住了。
使用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 :(得分: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
不是真正的列名,否则你会收到错误。