#put db connection code here

$sql	= "YOUR SQL HERE";
$res    = mysql_query($sql);

$header = false;
$out    = fopen('php://output', 'w');

while($row = mysql_fetch_assoc($res)) {
                if(!$header) {
                                $header = array_keys($row);
                                fputcsv($out,$header);
                }
                fputcsv($out,$row);
}
                
fclose($out);

$filename = 'something.csv';

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$filename";");