沃梦达 / 编程问答 / php问题 / 正文

PDO 准备好的语句 fetch() 返回双重结果

PDO prepared statement fetch() returning double results(PDO 准备好的语句 fetch() 返回双重结果)

本文介绍了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,约翰,约翰,史密斯,史密斯,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)).""
";
}
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)) 

获取由列号索引的数组

来自 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() 返回双重结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PDO 准备好的语句 fetch() 返回双重结果

基础教程推荐