What are the common pitfalls when generating CSV files from MySQL databases in PHP?

Common pitfalls when generating CSV files from MySQL databases in PHP include not properly handling special characters, not setting the correct headers for downloading the file, and not properly closing the file after writing data to it. To solve these issues, make sure to properly escape special characters, set the appropriate headers for CSV files, and close the file handle after writing data.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Query to fetch data from database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Set headers for CSV file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');

// Open file handle for writing CSV data
$fp = fopen('php://output', 'w');

// Write column headers to CSV file
fputcsv($fp, array('Column 1', 'Column 2', 'Column 3'));

// Write data from database to CSV file
while($row = mysqli_fetch_assoc($result)){
    fputcsv($fp, $row);
}

// Close file handle
fclose($fp);

// Close database connection
mysqli_close($connection);