What specific PHP functions can be utilized to efficiently save values from a database to a CSV file for Excel use?
To efficiently save values from a database to a CSV file for Excel use, you can use the fputcsv() function in PHP. This function formats a line as CSV and writes it to an open file. You can fetch the data from the database, loop through the results, and use fputcsv() to write each row to the CSV file.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Fetch data from the database
$stmt = $pdo->query("SELECT * FROM mytable");
// Open a file for writing
$fp = fopen('data.csv', 'w');
// Write column headers to the CSV file
fputcsv($fp, array('Column1', 'Column2', 'Column3'));
// Loop through the database results and write each row to the CSV file
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp, $row);
}
// Close the file
fclose($fp);