Here's the code I use for myself. Give it a try. Hope this helps.
<?
include('database_connection');
//clearing a file and starting fresh
$file = fopen("myfile.csv","w");
fputs($file,"");
fclose($file);
$sql = mysql_query("SELECT something from something where something = 'something'") or die (mysql_error());
while ($row = mysql_fetch_array($sql)){
$email = $row['email'];
$sentto = $row['username'];
$code = $row['password'];
$array = array("$email","$sentto","$code"."\r\n");
$comma_separated = implode(",", $array);
$file = fopen("myfile.csv","a");
fwrite($file,"$comma_separated");
}
fclose($file);
mysql_free_result($sql);
?>