Hello,
I have the below code that will export a MySQL query to a CSV (I grabbed it off a tutorial and modified a bit to my use). I am trying to modify it further so I can perform multiple select statements and output all of them to the same CSV. I am struggling a bit as I am new to PHP (I got the basic syntax, if, else, loops, etc. but that’s about it). Can anyone help?
[php]
<?php
//include database configuration file
include 'dbConfig.php';
//get records from database
$query = $db->query("SELECT FirstName, LastName, CellPhone, Email FROM `Person` WHERE JobTitle=1 AND PrimaryLocation=2 OR JobTitle=2 AND PrimaryLocation=2");
if($query->num_rows > 0){
$delimiter = ",";
$filename = "Store2" . date('Y-m-d') . ".csv";
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('FirstName', 'LastName', 'CellPhone', 'Email');
fputcsv($f, $fields, $delimiter);
//output each row of the data, format line as csv and write to file pointer
while($row = $query->fetch_assoc()){
$lineData = array($row['FirstName'], $row['LastName'], $row['CellPhone'], $row['Email']);
fputcsv($f, $lineData, $delimiter);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
exit;
?>
[/php]