问题描述
我有一个输出到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,2014Should be1,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))
获取由列号索引的数组
控制如何将下一行返回给调用方. 该值必须是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()返回双精度结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!