Export mySql Table to CSV using fputcsv and php

This is a great little mysql table to csv script I use to create a backup file of any table within a db.


$headings = array();
$q = mysql_query("select * from {table_name} where {conditions} ); 
for( $f=0; $f<mysql_num_fields($q); $f++ ){
        $headings[] .= mysql_field_name($q,$f);
}
$tableFile = "/path/to/bak/files/" . "filename_" . date("ymd") . ".csv", 'w');
        while( $row = mysql_fetch_array( $q ) ){
                $vals = array();
                foreach( $headings as $h ){
                        $vals[] .= $row[($h)];
                }
                fputcsv($tableFile,$vals);
                unset($vals);
        }
fclose($tableFile);

Basically you just decide on the path, and the table to export, then you can set a nice crons sript to run it via php, or grab it from the web whenever you need.

Tags: ,

Comments are closed.