Here is a full working example using PDO and including column headers:
$query = $pdo->prepare('SELECT * FROM test WHERE id=?');
$query->execute(array($id));
$results = $query->fetchAll(PDO::FETCH_ASSOC);
download_csv_results($results, 'test.csv');
exit();
function download_csv_results($results, $name)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. $name);
header('Pragma: no-cache');
header("Expires: 0");
$outstream = fopen("php://output", "wb");
fputcsv($outstream, array_keys($results[0]));
foreach($results as $result)
{
fputcsv($outstream, $result);
}
fclose($outstream);
}