1

这里有非常相似的问题,但是经过大量搜索和尝试不同的事情后,我仍然被卡住了。

用于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(),为什么要将值添加到数组中两次?

4

1 回答 1

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这不是一个真正的列名,否则你会得到一个错误。

于 2013-02-06T20:15:25.620 回答