PDO 准备语句 fetch() 返回双倍结果 [英] PDO prepared statement fetch() returning double results

查看:28
本文介绍了PDO 准备语句 fetch() 返回双倍结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输出到 CSV 文件的脚本.但是,即使数据库中当前只有一行,我得到的输出也会将表中每一行的每一列回显两次.

I have a script that is outputting to a CSV file. However, even though there is currently one row in the database, the output I'm getting is echoing out each column from each row in the table twice.

例如:1,1,John,John,Smith,Smith,2014,2014应该1,约翰,史密斯,2014

For example: 1,1,John,John,Smith,Smith,2014,2014 Should be 1,John,Smith,2014

在我使用 PDO 和准备好的语句之前,这很好用,所以我想也许我不理解 fetch() 是如何正确工作的.下面是我的代码.知道我可能做错了什么吗?

This worked fine before I went with PDO and prepared statements, so I'm thinking maybe I'm not understanding how fetch() works correctly. Below is my code. Any idea what I could be doing wrong?

// get rows
$query_get_rows = "SELECT * FROM Contacts ORDER BY date_added DESC";
$result_get_rows = $conn->prepare($query_get_rows);
$result_get_rows->execute();         
$num_get_rows = $result_get_rows->rowCount();

while ($rows_get_rows = $result_get_rows->fetch()) 
{
  $csv .= '"'.join('","', str_replace('"', '""', $rows_get_rows))."\"\n";
}
echo $csv;
exit;

推荐答案

你应该对 PDO 说,你只需要一个关联数组或编号数组:

You should say to PDO, that you want only an associative array or a numbered array:

while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_ASSOC)) 

获取关联数组或

while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_NUM)) 

获取以列号为索引的数组

to get an array indexed by the column number

来自PDOStatement::fetch

fetch_style

fetch_style

控制下一行如何返回给调用者.该值必须是 PDO::FETCH_* 常量之一,默认为PDO::ATTR_DEFAULT_FETCH_MODE 的值(默认为PDO::FETCH_BOTH).

Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH).

PDO::FETCH_ASSOC:返回一个按返回的列名索引的数组在你的结果集中

PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

PDO::FETCH_BOTH(默认):返回由两列索引的数组结果集中返回的名称和 0 索引列号

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

这篇关于PDO 准备语句 fetch() 返回双倍结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆