Export Query Results to CSV
Description: Queries a multi-row result set and writes it to a CSV file for export.
SQL
// Query the data you want to export
$rows = $this->query(
"SELECT C.FIRST_NAME, C.LAST_NAME, CE.EMAIL
FROM CONTACTS C
LEFT JOIN CONTACTS_EMAILS CE ON C.RECID = CE.CONTACTS_RECID
WHERE C.ACTIVE = :active",
[":active" => "1"]
);
// Build CSV — arrayToCsv handles one flat row at a time, so loop over results
$csv = $this->arrayToCsv(['First Name', 'Last Name', 'Email']);
foreach ($rows as $row) {
$csv .= $this->arrayToCsv([
$row['FIRST_NAME'],
$row['LAST_NAME'],
$row['EMAIL'],
]);
}
$this->createFile('contacts_export.csv', $csv);
$response['message'] = 'Export complete: contacts_export.csv';
Key patterns: $this->arrayToCsv() accepts a single flat row — loop over result rows and concatenate; write the finished string with $this->createFile()