PHP Code:
// make a back up to CSV files
$tables = array('table1', 'table2', 'table3');
foreach($tables as $table){
$query = "SELECT * FROM $table";
$query_result = mysql_query($query) or die ('Table: '. $table .' - Error: '. mysql_error());
$csv_contents = '';
if(mysql_num_rows($query_result) > 0){
while($row = mysql_fetch_assoc($query_result)){
$i = 0;
foreach($row as $v){ // creates this: "value one","value two","value three"
$csv_contents .= ($i) ? ',' : '';
$i++;
$csv_contents .= '"'.addslashes($v).'"';
}
$csv_contents .= "\r\n";
}
}
$backup_file = $_SERVER['DOCUMENT_ROOT'].str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']).'../backup/'.$table.'_backup.csv';
$fp = @fopen($backup_file, 'w') or die('Could not create/open ' . $backup_file);
fwrite($fp, $csv_contents, strlen($csv_contents));
fclose($fp);
}
echo 'Done!';
PHP Code:
// reload the backup into empty tables
$tables = array('table1', 'table2', 'table3');
foreach($tables as $table){
$backup_file = $_SERVER['DOCUMENT_ROOT'].str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']).'../backup/'.$table.'_backup.csv';
$query = "load data infile '$backup_file'
into table $table
fields terminated by ','
enclosed by '\"'
lines terminated by '\r\n'";
$query_result = mysql_query($query) or die (mysql_error());
}
echo 'Done!';
Bookmarks