使用PDO获取数据会返回重复的结果

时间:2014-04-06 14:38:17

标签: php mysql pdo fetch

我有这段代码:

...
$query->setFetchMode(PDO::FETCH_INTO, $this);
$query->execute();
$data = array();
while ($row = $query->fetch()) {
    $data[] = $row;
}
return $data;

如果我把var_dump放在这里:

var_dump($data);
return $data;

结果如下:

array (size=3)
  0 =>
    object(ChatRoom)[4]
        public 'id' string '3' (length=1)
        ...
  1 =>
    object(ChatRoom)[4]
        public 'id' string '3' (length=1)
        ...
  2 =>
    object(ChatRoom)[4]
        public 'id' string '3' (length=1)
        ...

如果我把var_dump放在这里:

while ($row = $query->fetch()) {
    $data[] = $row;
    var_dump($data);
}

结果如下:

array (size=1)
  0 =>
    object(ChatRoom)[4]
        public 'id' string '1' (length=1)
        ...
array (size=2)
  0 =>
    object(ChatRoom)[4]
        public 'id' string '2' (length=1)
        ...
  1 =>
    object(ChatRoom)[4]
        public 'id' string '2' (length=1)
        ...
array (size=3)
  0 =>
    object(ChatRoom)[4]
        public 'id' string '3' (length=1)
        ...
  1 =>
    object(ChatRoom)[4]
        public 'id' string '3' (length=1)
        ...
  2 =>
    object(ChatRoom)[4]
        public 'id' string '3' (length=1)
        ...

我尝试了fetchAll但结果却一样。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您正在尝试使用您不需要的功能。

$query->setFetchMode(PDO::FETCH_INTO, $this);

删除此行^