I have a PHP script that I use to run a query in mysql and export a file. I have the login credentials within the php file. It will be invoked by a user visiting the page and the file automatically downloads. I have read that you should write the credentials in another file and include it in the file. I don't know enough about php to know where to store this file securely and how to properly include it. I had a friend help me write the file.
The php script is as follows.
<?php
header("Access-Control-Allow-Origin: *");
$db_user = "user"; //replace with your mysql username
$db_pass = "password"; //replace with your mysql password
$db_source = "database"; //replace with your database name
$mysqli = mysqli_connect("localhost", $db_user, $db_pass, $db_source);
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
} else {
// place sql query between quotes for $sql -- do not end with ;
$sql = " SQL Statement Here ";
$res = mysqli_query($mysqli, $sql);
$rows = array();
if ($res) {
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
} else {
printf("Could not retrieve records: %s
", mysqli_error($mysqli));
}
$return = array(
$rows
);
array_to_csv_download($rows);
mysqli_free_result($res);
mysqli_close($mysqli);
unset ($db_user, $db_pass, $db_source);
}
function array_to_csv_download($array, $filename = "export.csv", $delimiter=",") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
?>