This is the code I'm using:
<?php
// declare the variables for access
// database to be exported
$db = 'BLANK';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'db_export_'.$db.'_'.date('Y-m-d').'.csv';
// database variables
$hostname = "BLANK";
$user = "BLANK";
$password = "BLANK";
$database = "BLANK";
$port = BLANK;
$conn = mysqli_connect($hostname, $user, $password, $database, $port);
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysqli_query($conn, "SELECT * FROM ".$db." ".$where);
$field = mysqli_field_count($conn);
// create line with field names
for($i = 0; $i < $field; $i++) {
$csv_export.= mysqli_fetch_field_direct($query, $i)->name.';';
}
// newline
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysqli_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysqli_fetch_field_direct($query, $i)->name].'";';
}
$csv_export.= '
';
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>
It's not really giving me the result I expected, but instead producing a csv file with table information such as:
( ! ) Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result boolean given in C:\wamp64\www\cronjob\TestJob1.php on line 33 Call Stack
#TimeMemoryFunctionLocation 10.0145244752{main}( )...\TestJob1.php:0 20.1295255904http://www.php.net/function.mysqli-fetch-array' target='_new'>mysqli_fetch_array ( )...\TestJob1.php:33
which came as a different format in the csv, involving strange table row/column and color declarations. I'm not actually sure about the exact error though, because my line 33 is just a comment, and I would greatly appreciate any help. Information such as username and password are blanked out on purpose.