PDO Prepared Statement Fetching Double Results
A user has encountered an issue where their PDO prepared statement is returning double results when outputting data to a CSV file. The code in question utilizes the $result_get_rows->fetch() function to retrieve the rows from the database.
Understanding the Fetch() Method
The fetch() method of a PDOStatement object is used to retrieve rows from a result set. By default, it returns rows as both indexed arrays (by column number) and associative arrays (by column name).
Resolving the Issue
To rectify the double results, it is recommended to specify how the result rows should be returned using the fetch_style parameter of the fetch() method. This parameter accepts one of the following constants:
Modified Code
By using PDO::FETCH_ASSOC, the code can be modified as follows:
while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_ASSOC)) {
$csv .= '"'.join('","', str_replace('"', '""', $rows_get_rows))."\"\n";
}
This modification will ensure that the rows are returned as associative arrays, effectively preventing the duplication of values when outputting to the CSV file.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3