I have an application that I need to add a function to that will download a complete MySql Table in comma delineated format from a web site to a local hard drive. What is the best way to do this?Here's a function I've used to spit out csv files. You can modify it to actually write the csv file to a directory. I use this function to build those files on the fly because I never need to save them. Pass the function your mysql query and a default filename that a user will save the file as. Also you'll need to connect to the database before you call the function.
Is there a function in PHP that will do this? in MySql? or do I just need to do something with fopen().
Anything to help me get started would be appreciated.
Mark Roberts Sr. Systems Analyst
function mysql_export_csv($query,$filename) { header("Content-Type: text/csv"); header("Content-Disposition: attachment; filename=".$filename); $result = mysql_query($query) or die( mysql_error() ); $number_cols = mysql_num_fields($result);
for ($i=0; $i < $number_cols; $i++) {
if ($i) echo ","; /* Insert comma before next field only
* if not on the first column
*/
echo"\"" . mysql_field_name($result, $i). "\"";
}
echo "\n";
while($row = mysql_fetch_array($result)) {
for ($i=0; $i < $number_cols; $i++) {
if ($i) echo ","; /* Insert comma before next field only
* if not on the first column
*/
if (($row[$i]) == NULL) {
// Do nothing
} else if ($row[$i] === "0") { /* === operand verifies type and value */
echo "\"0\"";
} else if ($row[$i] === 0) { /* === operand verifies type and value */
echo "\"0\"";
} else if ($row[$i] === "") { /* === operand verifies type and value */
echo "\"\"";
} else {
/** I get here it's not an empty string and it's not a zero;
* otherwise, if I don't check... $values do not print if they are zero
*/
echo"\"" .str_replace("\"","\"\"",$row[$i]). "\"";
}
}
echo "\n";
}
}
to use:
mysql_export_csv($MyQuery,"MyReport.csv");
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php