What are the potential benefits of exporting MySQL data to .csv using PHP?
Exporting MySQL data to .csv using PHP can be beneficial for various reasons. It allows for easy data manipulation and analysis in spreadsheet software, simplifies data sharing with others, and provides a convenient way to create backups of database information. By using PHP to automate the export process, you can save time and ensure consistency in the exported data format.
<?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 select data from MySQL table
$query = "SELECT * FROM table_name";
$result = $mysqli->query($query);
// Create and open .csv file for writing
$fp = fopen('exported_data.csv', 'w');
// Write column headers to .csv file
fputcsv($fp, array('Column1', 'Column2', 'Column3'));
// Loop through MySQL results and write each row to .csv file
while ($row = $result->fetch_assoc()) {
fputcsv($fp, $row);
}
// Close .csv file and MySQL connection
fclose($fp);
$mysqli->close();
echo "Data exported to .csv file successfully!";
?>