What are the best practices for exporting MySQL database results to a CSV file using PHP?
When exporting MySQL database results to a CSV file using PHP, it is important to properly format the data and handle any special characters. One way to achieve this is by looping through the database results and using fputcsv() function to write each row to the CSV file.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Query to fetch data from database
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
// Open a file handle for writing
$fp = fopen('export.csv', 'w');
// Write column headers to CSV file
fputcsv($fp, array('Column1', 'Column2', 'Column3'));
// Loop through database results and write to CSV file
while ($row = $result->fetch_assoc()) {
fputcsv($fp, $row);
}
// Close file handle and database connection
fclose($fp);
$mysqli->close();
?>
Related Questions
- In what ways can PHP forums or communities differentiate between beginner and advanced users to provide more targeted assistance and resources for each group?
- What are the common pitfalls of not properly structuring PHP code within a while loop?
- Are there any best practices for handling line breaks when reading files in PHP?