To fetch data from a MySQL database and export it to CSV using PHP, you can follow these steps:
<?php
// Database connection details
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from your table
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
// Check if any rows are returned
if ($result->num_rows > 0) {
// Define CSV filename
$filename = "exported_data.csv";
// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
// Create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// Output CSV header
$header = array('ID', 'Name', 'Email');
fputcsv($output, $header);
// Output data from rows
while ($row = $result->fetch_assoc()) {
fputcsv($output, $row);
}
// Close the file pointer
fclose($output);
} else {
echo "No data found";
}
// Close the database connection
$conn->close();
?>
Explanation:
- Database Connection: Replace your_username, your_password, your_database_name, and your_table with your actual database credentials
- and table name.
- Fetch Data: The SQL query retrieves data from the specified table.
- CSV Headers: The header function is used to set headers for CSV download.
- CSV File Creation: We use fopen to create a file pointer connected to the output stream (php://output). Then, fputcsv is used to write the
- CSV header and data.
- Download CSV: Headers are set to prompt the user to download the CSV file with the specified filename.
- When you run this script, it will fetch data from your MySQL table and export it to a CSV file, which will be downloaded by the user.