Something like this should work:
$linkID = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname, $linkID);
$table="table_name";
// Build rows of data
$query = "SELECT * FROM `$table`";
$result = mysql_query($query, $linkID);
while($row = mysql_fetch_array($result))
{
for($i=0;$i<mysql_num_fields($result);$i++)
{
$string .= $row[$i];
if($i!=mysql_num_fields($result)-1)$string.=','; // Add a comma after all fields except for the last one
}
$string.="\n"; // Add a new line character at the end of the line
}
// Write $string to file
$filename="database_export.csv";
$fh = fopen($filename, "w+");
if(fwrite($fh, $string)) echo "Write successful";
else echo "Write failed";
fclose($fh);