Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- backup_tables('host','username','password');
- /* backup the db OR just a table */
- function backup_tables($host,$user,$pass,$name,$tables = '*')
- {
- $link = mysql_connect($host,$user,$pass);
- mysql_select_db($name,$link);
- //get all of the tables
- if($tables == '*')
- {
- $tables = array();
- $result = mysql_query('SHOW DATABASES');
- while($arr = mysql_fetch_array($result))
- {
- $result2 = mysql_query('SHOW TABLES FROM '.$arr[0]);
- while($row = mysql_fetch_row($result2))
- {
- $tables[$arr[0]][] = $row[0];
- }
- }
- }
- else
- {
- $tables = is_array($tables) ? $tables : explode(',',$tables);
- }
- /*A little middle check, to see if all is saved in the right way*/
- /*$k=0;
- foreach($tables as $database => $tab){
- echo "<p style='font-weight: bold;text-transform: uppercase;'>$database</p><br/>";
- print_r($tab);
- echo '<br/>';
- }*/
- //cycle through
- mkdir('backup_'.date('Y-m-d'));
- foreach($tables as $database => $tab){
- $return = '';
- foreach($tab as $table){
- $result = mysql_query('SELECT * FROM `'.$database.'`.`'.$table.'`');
- $num_fields = mysql_num_fields($result);
- //$return.= 'DROP TABLE `'.$database.'`.`'.$table.'`;';
- $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE `'.$database.'`.`'.$table.'`'));
- $return.= "\n\n".$row2[1].";\n\n";
- for ($i = 0; $i < $num_fields; $i++)
- {
- while($row = mysql_fetch_row($result))
- {
- $return.= 'INSERT INTO `'.$database.'`.`'.$table.'` VALUES(';
- for($j=0; $j<$num_fields; $j++)
- {
- $row[$j] = addslashes($row[$j]);
- $row[$j] = ereg_replace("\n","\\n",$row[$j]);
- if($row[$j] == '')
- $val = "NULL";
- else
- $val = $row[$j];
- if (isset($row[$j])) { $return.= '"'.$val.'"' ; } else { $return.= 'NULL'; }
- if ($j<($num_fields-1)) { $return.= ','; }
- }
- $return.= ");\n";
- }
- }
- $return.="\n\n\n";
- }
- $handle = fopen('backup_'.date('Y-m-d').'/'.$database.'.sql','w+');
- fwrite($handle,$return);
- fclose($handle);
- }
- //save file
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement