Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

php - PDO prepared statement fetch() returning double results

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.

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

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)) 

to get an associative array or

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

to get an array indexed by the column number

from PDOStatement::fetch

fetch_style

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: returns an array indexed by column name as returned in your result set

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...