I'm trying to make a CSV file out of my query result but I need to format the data first before writing it to the CSV.
I have a working code which prints the whole row to csv and is working fine.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('ID', 'Name', 'Country', 'Province/City' 'Address', 'Gender', 'Track', 'Payment Option'));,
$sql = "SELECT * FROM STUDENTINFO order by GRADELEVEL";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
fputcsv($output, $row);
}
fclose($output);
I understand that the code above ouputs the complete row. But is there way to format specific fields first before writing to csv?
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$name = $row['FIRSTNAME']." ".$row['MIDDLENAME']." ".$row['LASTNAME'];
$gradelevel = glvlDESCRIPTION(row['GRADELEVEL']);
if ($row['TRACK'] == "AW")
{
$track = "A With Activities";
}
else
{
$track = "A Without Activities";
}
fputcsv($output, $row['STUDENTID'], $name, $row['COUNTRY'], $row['PROVINCE'], $row['ADDRESS'], $track...);
}
fclose($output);