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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 20:47:30281browse

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>

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!

Statement:
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