Techno

MySQL database dump creator - PHP

Apr 4th, 2011
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. <?php
  2. function mysqldump($DBhost,$DBuser,$DBpass,$DBname,$tables = '*'){
  3.     $connect = mysql_connect($DBhost,$DBuser,$DBpass);
  4.     mysql_select_db($DBname,$connect);
  5.     if($tables == '*'){
  6.         $tables = array();
  7.         $result = mysql_query('SHOW TABLES');
  8.         while($row = mysql_fetch_row($result)){
  9.             $tables[] = $row[0];
  10.         }
  11.     }
  12.     else{
  13.         $tables = is_array($tables) ? $tables : explode(',',$tables);
  14.     }
  15.     if(!is_array($tables))$tables[] = $tables;
  16.     foreach($tables as $table){
  17.         $return .= "\n\n-- DUMPING TABLE $table --";
  18.         $result = mysql_query('SELECT * FROM '.$table);
  19.         $num_fields = mysql_num_fields($result);
  20.         $return .= "\n\nDROP TABLE IF EXISTS `".$table."`;";
  21.         $row2 = mysql_fetch_row(mysql_query("SHOW CREATE TABLE ".$table));
  22.         $return .= "\n\n".$row2[1].";";
  23.         for($i=0;$< $num_fields; $i++){
  24.             while($row = mysql_fetch_row($result)){
  25.                 $return.= "\n\nINSERT INTO `".$table."` VALUES (";
  26.                     for($j=0; $j<$num_fields; $j++){
  27.                         $row[$j] = addslashes($row[$j]);
  28.                         $row[$j] = preg_replace("@\n@","\\n",$row[$j]);
  29.                         if(isset($row[$j])){ $return.= '"'.$row[$j].'"';}
  30.                         else{$return.= '""';}
  31.                         if ($j<($num_fields-1)){$return.= ',';}
  32.                     }
  33.                 $return.= ");";
  34.             }
  35.         }
  36.         $return .= "\n\n";
  37.     }
  38.     file_put_contents('tech-db-backup-'.time().'.sql',$return);
  39. }
  40. ?>
Add Comment
Please, Sign In to add comment