Jump to content

HOW:Code to automatically export sql table as CSV & save file name by date/time?


ghurty

Recommended Posts

I have a php script that makes a lot of entries into a sql table.

The problem is that each time it runs it erases the previous entries.

 

What code can I put in the script so that when it finishes running, it will export the table (preferably as a CSV) and save it with a file name based on date/time?

 

 

Thanks

Here's a really terrible way to generate a CSV and dump it to the browser

 

<?php
error_reporting(E_NONE);

/** Connection stuff...
* 
* 
* 
*/


/** Your table here */
$table = ""; 

$query = mysql_query("SELECT * FROM {$table} LIMIT 1");

foreach(mysql_fetch_assoc($query) as $key => $val)
    $csv_col[] = '"'. $key .'"';

$cols = implode(", ", $csv_col) ."\n";
$query = mysql_query("SELECT * FROM {$table}");
while($row = mysql_fetch_row($query))
{
    foreach($row as $val)
    {
        $csv_row[] = '"'. trim($val) .'"';    
    }
    
    $rows .= implode(", ", $csv_row) ."\n";
    
    $csv_row = array();
}
        
print_r($cols.$rows);
                
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.