PHP code to convert a MySQL query to CSV
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Exporting a MySQL query to CSV in PHP is usually just a loop: run the query, fetch rows, and write them with fputcsv. The important parts are using a proper database API, handling headers and encoding deliberately, and streaming the output so large exports do not consume too much memory.
Query with PDO and Stream the Output
A clean PDO-based example looks like this:
fputcsv handles proper field quoting, which is one reason it is better than building CSV lines by string concatenation.
Send It as a Download
If the goal is a browser download, add headers before writing output:
Then keep writing to php://output. This streams the CSV directly to the client instead of creating a temporary file first.
Keep the Query Safe and Explicit
If the query uses user input, switch from query() to a prepared statement:
Security matters here because export endpoints often feel “internal” and then quietly become externally reachable later.
Handle Large Exports as Streams
For large result sets, streaming row by row is the right default. It avoids loading the full result into memory before writing the CSV.
That is why a fetch loop plus fputcsv is usually better than fetching all rows into an array first.
Decide Whether to Include a Header Row
Many CSV consumers expect column names on the first line. If you know the schema up front, write them explicitly. If the columns are dynamic, you may need to inspect the first row or query metadata and then emit a matching header line.
The key is to be deliberate. Some integrations want headers, some do not.
CSV Shape Is Part of the Contract
Think about how downstream tools will consume the file. Column order, header names, delimiter expectations, and newline behavior are all part of whether the export is actually useful once it leaves PHP.
Writing to a File Uses the Same Core Pattern
If the CSV should be saved on disk instead of streamed to the browser, open a real file handle rather than php://output and keep the same fputcsv loop. The export logic stays the same; only the destination changes.
Common Pitfalls
- Building CSV lines manually instead of using
fputcsv. - Fetching the full query result into memory before writing the export.
- Forgetting download headers when the output should be a browser file download.
- Using raw user input in the query instead of prepared statements.
- Ignoring encoding and then being surprised when spreadsheet software displays characters incorrectly.
Spreadsheet Consumers Often Have Extra Expectations
Some CSV consumers care about UTF-8 BOMs, delimiter choice, or line-ending conventions. The export loop may be correct while the receiving tool still looks wrong because its CSV expectations differ from yours.
Summary
- Run the query, fetch rows, and write them with
fputcsv. - Use PDO and prepared statements for safer database access.
- Stream to
php://outputfor browser downloads and large exports. - Set CSV response headers when the result should download immediately.
- Let
fputcsvhandle quoting instead of manually building lines.
Related reading
- PHP date format when inserting into datetime in MySQL
- PHP MySQL Google Chart JSON - Complete Example
- PHP MySQL transactions examples
- php mysqli_connect authentication method unknown to the client caching_sha2_password
- PHP PDO charset, set names?
- PHP with MySQL 8.0 error The server requested authentication method unknown to the client
- phpMyAdmin - Error Incorrect format parameter?
- phpmyadmin logs out after 1440 secs

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.