I have the following query...
public function get_invoice_user_summary_csv($invoice_table_id)
{
$sql_get_user_summ = "
SELECT `billingHistory`.`$invoice_table_id`.userId as userId, ipCore.users.firstname, ipCore.users.surname, COUNT(`billingHistory`.`$invoice_table_id`.id) AS totalNum, SUM(`billingHistory`.`$invoice_table_id`.durationSeconds) AS totalDuration, (SUM(`billingHistory`.`$invoice_table_id`.priceMin)+SUM(`billingHistory`.`$invoice_table_id`.priceCon)) AS totalCost
FROM `billingHistory`.`$invoice_table_id`
LEFT JOIN ipCore.users ON `billingHistory`.`$invoice_table_id`.userId = ipCore.users.id
GROUP BY userId
ORDER BY ipCore.users.surname ASC, ipCore.users.firstname ASC;";
$query = $this->db_mtvm->query($sql_get_user_summ);
if($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$line = '';
$value = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = ",";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . ",";
}
$line .= $value;
}
print substr(str_replace("\r", "", trim($line)), 0, -1)."\r\n";
flush();
ob_flush();
}
}
else return false;
}
this return formatted array for csv out put in a different controller.
however it is just the body of data (as i expected). However I have read a few questions with i think similar things, but canot quite work out in this example where I need to put the column headings. either manually entered, or I will assign these from the sql query.
You now loop through the results, by doing this:
foreach ($query->result_array() as $row)
You should change your script so that on the first iteration of this loop, you fetch the column headers and output them. A quick way to do this would be to change the line I quoted above to:
$i = 0;
foreach ($query->result_array() as $row)
{
if($i === 0)
echo implode(",", array_keys($row)) . "\r\n";
$i++;
[...]
I notice you're creating the CSV string yourself. An easier way to do that is by using fputcsv()
. By default it writes to a file handle, but you can also buffer the output in memory and fetch the result as a string, like this example shows .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.