PDO prepared fetch () statement returning double results

I have a script that outputs to a CSV file. However, although there is one row in the database in the database, the output I get is repeated every column of each row in the table twice.

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

This worked fine before I went with PDO and prepared statements, so I think maybe I don’t understand how fetch () works correctly. Below is my code. Any idea what I can do 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; 
+7
php mysql pdo fetch
source share
1 answer

You should tell PDO that you only want 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 column number

from PDOStatement :: fetch

fetch_style

Controls how the next line is returned to the caller. This value must be one of the constants PDO :: FETCH_ *, the default value is PDO :: ATTR_DEFAULT_FETCH_MODE (by default 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 columns name and 0-index column number returned in your result set

+16
source share

All Articles