I am going to try and do this the way you have started and will try to explain what i did. First I'm not going to show the login for the database so the file starts at line : $table = 'maptable'; //Table name
First I added this line on top: $csv_output = ""; because the first time you use the string we get an error. Your adding to a string that is not defined so this defines it. And changed this line: $file = 'csvexport.cvs'; I added the extension here (easier) and changed the lines in code to reflect this.
Next all this:
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
echo mysql_num_rows($result).'<br />';
while ($row = mysql_fetch_assoc($result)) {
$i++;
}
}
is just taking up space and time setting $i to the number of columns. I deleted it and used this:
$query = "SELECT * FROM $table";
$result = mysql_query($query);
$i = mysql_num_fields($result); this line is a lot less work.
At the end of the code I removed : readfile('csvexport.cvs'); because the display has no line feeds and looks bad.
And : if(file_exists($file.'.csv')){return (1);}else{return(0);} If you want it back do it. A simple echo file saved is good here.
lastly you aren't writing headers cause you never got the headers. $rowr = mysql_field_name($result, $j); will get them.
Here's the final code:
----------------------------
<?php
$csv_output = "";
$table = "clan_registry"; //Table name
$file = 'csvexport.cvs'; //CSV File name
$query = "SELECT * FROM $table";
$result = mysql_query($query);
$colCount = mysql_num_fields($result); //this is the colCount
$i = $colCount;
for($j = 0; $j < $i; $j++)
{
$rowr = mysql_field_name($result, $j);
$csv_output .= '"' . $rowr . "\",";
}
//$csv_output .= '"' . $rowr. "\"";
$csv_output .= "\n";
while ($rowr = mysql_fetch_row($result))
{
for ($j=0;$j<$i-1;$j++)
{
$csv_output .='"'.$rowr[$j]."\",";
}
$csv_output .='"'.$rowr[$j]."\"";
$csv_output .= "\n";
}
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $csv_output);
fclose($fh);
?>