I've been looking for ways to enable EXPORT feature for my database website. My goal is to construct a very simple PHP code to do this, all it needs is to export the contents of one of my MySQL tables to the user's desktop or give the user a clickable link so he can download the exported database. The DB must be in Excel/CSV (As I will be using this feature for import/export DB backup feature as well).
I saw fputcsv() and other old methods like mysql (instead of mysqli) codes but all fails, some created a CSV file on server's directory while other methods simple gives an error like
explode() expects parameter 2 to be string, object given in
or
fputcsv() expects parameter 2 to be array, null given in
I feel this should have been simple but what is the best way or code to use for export DB feature?
EDIT:
After combining and testing series of options, I was able to solve it. I am sharing here so those who will experience my dilemma will not have a hard time like I did :(
When the user clicks the EXPORT button, Chrome browser automatically downloads a CSV file which contains a copy of the database including the field names.
<?php
include('/connectme.php');
$thequery = "SELECT * FROM members";
$result = mysqli_query($conn,$thequery);
$file = fopen("php://output","w");
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="exported.' . date("Y.m.d") . '.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$emptyarr = array();
$fieldinf = mysqli_fetch_fields($result);
foreach ($fieldinf as $valu)
{
array_push($emptyarr, $valu->name);
}
fputcsv($file,$emptyarr);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($file,$row);
}
fclose($file);
mysqli_free_result($result);
mysqli_close($conn);
?>