This article demonstrate how we can export records from MySQL Table to a CSV file. fputcsv() is a buit in function of PHP which takes an array and a file pointer as parameters which convert the array data into CSV format and writes it to the file.
In the below code first we create a file pointer using fopen() and set the value for Content-type and Content-Disposition in header(). And then, pass file pointer and array of database records into fputcsv() to generate CSV file.
<?php
$host = 'hostname';
$user = 'username';
$password = 'password';
$database = 'database_name';
$table = 'table_name';
//Connect to database
$con = mysqli_connect($host, $user, $password, $database);
$filename = "sample.csv";
$file = fopen('php://output', 'w');
//To fetch column names of table
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='".$database."' AND TABLE_NAME='".$table."'";
$result = mysqli_query($con, $query);
while ($res = mysqli_fetch_row($result)) {
$header[] = $res[0];
}
//Generate CSV file
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($file, $header);
//To fetch records from table
$query = "SELECT * FROM $table";
$result = mysqli_query($con, $query);
while($data = mysqli_fetch_row($result)) {
fputcsv($file, $data);
}
fclose($file);
?>
0 Comment(s)