How can you ensure that the CSV file includes column names in the first row when exporting data from a MySQL database?
When exporting data from a MySQL database to a CSV file using PHP, you can ensure that the column names are included in the first row by manually adding them before fetching the data. This can be done by fetching the column names from the MySQL result set and then appending them to the CSV file before looping through the data rows.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to fetch data
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Create CSV file
$csv_file = fopen('export.csv', 'w');
// Add column names to CSV file
$columns = [];
while ($field = mysqli_fetch_field($result)) {
$columns[] = $field->name;
}
fputcsv($csv_file, $columns);
// Add data rows to CSV file
while ($row = mysqli_fetch_assoc($result)) {
fputcsv($csv_file, $row);
}
// Close file and database connection
fclose($csv_file);
mysqli_close($connection);
?>