Home > Database > Mysql Tutorial > Why is my PDO Prepared Statement Fetch() Duplicating Results?

Why is my PDO Prepared Statement Fetch() Duplicating Results?

Barbara Streisand
Release: 2024-11-01 20:47:30
Original
398 people have browsed it

Why is my PDO Prepared Statement Fetch() Duplicating Results?

PDO Prepared Statement Fetch() Duplicating Results

Issue

A PHP script using PDO prepared statements and fetch() is outputting duplicate data to a CSV file. Each row from the database is echoed twice, resulting in doubled column values.

Analysis

Previously, when not using PDO, the query worked as expected. Therefore, the issue may lie in the usage of fetch().

Resolution

By specifying the desired data retrieval mode when calling fetch(), the duplicate results issue can be resolved. There are two options:

  • PDO::FETCH_ASSOC: Returns an array indexed by the column names.
  • PDO::FETCH_NUM: Returns an array indexed by the column numbers.

To implement this, modify the code as follows:

<code class="php">while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_ASSOC)) {
  $csv .= '"'.join('","', str_replace('"', '""', $rows_get_rows))."\"\n";
}</code>
Copy after login

The above is the detailed content of Why is my PDO Prepared Statement Fetch() Duplicating Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template