I'm able to export the CSV with the heading and data (only if the data consist of more than 2 rows). If the it only has 1 row of data, only the header will be displayed and not the values. I'm not sure why. There's nothing wrong with the codes - can be compiled and run. Most likely to be code logic, but I don't see it.
function exportCases($export_company, $export_day, $export_month, $export_year) {
$dbMgr = new dbManager();
$conn = $dbMgr->getDBConnection();
$queries = "select * from case_report where ";
if($export_day != 0) {
$queries .= "day(start_date) = ".$export_day;
}
if($export_month != 0) {
if($export_day != 0) {
$queries .= " and ";
}
$queries .= "month(start_date) = ".$export_month;
}
if($export_year != 0) {
if($export_month != 0 || $export_day != 0) {
$queries .= " and ";
}
$queries .= "year(start_date) = ".$export_year;
}
if($export_company != 'default') {
if($export_day != 0 || $export_month != 0 || $export_year != 0) {
$queries .= " and ";
}
$export_company = "'".$conn->real_escape_string($export_company)."'";
$queries .= "company_id = ".$export_company;
}
// Fetch Record from Database
$output = "";
$table = ""; // Enter Your Table Name
$sql = $queries;
$rs=$conn->query($sql);
if($rs === false) {
print "<br />";
die ('Error in executing query: '.$conn->error);
} else {
$rows_returned = $rs->num_rows;
if($rows_returned == 0) {
return null;
}
}//end else
$columns_total = mysqli_num_fields($rs);
$firstRow = mysqli_fetch_assoc($rs);
$fields = array_keys($firstRow);
// Get The Field Name
foreach($fields as $r) {
$heading = $r;
$output .= '"'.$heading.'",';
}
$output .="\r\n";
// Get Records from the table
while($row = $rs->fetch_array()){
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\r\n";
}//end while
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}//exportCases
EDITED: added the foreach() code.
// Get Records from the table
foreach($fields as $f) {
$output .='"'.$firstRow[$f].'",';
}
while($row = $rs->fetch_array()){
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\r\n";
}//end while
$queries;
right before$sql = $queries;
and see what that outputs when there is just 1 row in the table. Then run that query in the query window and see if that returns anything. – asprin Jun 2 at 4:05$row = mysqli_fetch_assoc($rs);
will fetch the first row. And you never output the values. You just use the keys for $fields – WizKid Jun 2 at 4:07