What are some common methods for extracting data from a database and writing it to a .csv file using PHP?
To extract data from a database and write it to a .csv file using PHP, you can use SQL queries to fetch the data from the database and then use fputcsv function to write the data to a .csv file. You can loop through the fetched data and write each row to the .csv file.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Fetch data from the database
$stmt = $pdo->query('SELECT * FROM table_name');
// Open a file handle for writing
$fp = fopen('data.csv', 'w');
// Write column headers to the file
fputcsv($fp, array('Column1', 'Column2', 'Column3'));
// Loop through the fetched data and write each row to the file
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp, $row);
}
// Close the file handle
fclose($fp);
?>
Keywords
Related Questions
- What are the best practices for handling multiple HTTP requests in PHP to avoid overloading the server?
- What potential issues can arise from relying on the User Agent for login and session management in PHP applications?
- What are the potential drawbacks of using URL parameters as a form of access control for a website in PHP?