verrary

MysqlDump

Dec 2nd, 2014
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | None | 0 0
  1. <?php
  2. backup_tables('localhost','DB_USER','PASSWORD','DB_NAME');
  3. /* backup the db OR just a table */
  4. function backup_tables($host,$user,$pass,$name,$tables = '*')
  5. {   $link = mysql_connect($host,$user,$pass);
  6.     mysql_select_db($name,$link);
  7.     //get all of the tables
  8.     if($tables == '*')
  9.     {
  10.         $tables = array();
  11.         $result = mysql_query('SHOW TABLES');
  12.         while($row = mysql_fetch_row($result))
  13.         {
  14.             $tables[] = $row[0];
  15.         }
  16.     }
  17.     else
  18.     {
  19.         $tables = is_array($tables) ? $tables : explode(',',$tables);
  20.     }
  21.     //cycle through
  22.     foreach($tables as $table)
  23.     {
  24.         $result = mysql_query('SELECT * FROM '.$table);
  25.         $num_fields = mysql_num_fields($result);
  26.        
  27.         $return.= 'DROP TABLE '.$table.';';
  28.         $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
  29.         $return.= "\n\n".$row2[1].";\n\n";
  30.        
  31.         for ($i = 0; $i < $num_fields; $i++)
  32.         {
  33.             while($row = mysql_fetch_row($result))
  34.             {
  35.                 $return.= 'INSERT INTO '.$table.' VALUES(';
  36.                 for($j=0; $j<$num_fields; $j++)
  37.                 {
  38.                     $row[$j] = addslashes($row[$j]);
  39.                     $row[$j] = ereg_replace("\n","\\n",$row[$j]);
  40.                     if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
  41.                     if ($j<($num_fields-1)) { $return.= ','; }
  42.                 }
  43.                 $return.= ");\n";
  44.             }
  45.         }
  46.         $return.="\n\n\n";
  47.     }
  48. //save file
  49. $handle = fopen('backup-'.'_'.$name.'.sql','w+');
  50. fwrite($handle,$return);
  51. fclose($handle);
  52. echo "Done File name <br> http://".$_SERVER['HTTP_HOST'].'/'.basename(dirname(__FILE__)).'/backup'.'_'.$name.'.sql';
  53. }
  54. ?>
  55. <br/>
  56. <a href="MysqlDump.php">MysqlDump.php</a>
Add Comment
Please, Sign In to add comment