Backup your MySQL database


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. backup_tables('localhost','username','password','blog');
  2.  
  3.  
  4. /* backup the db OR just a table */
  5. function backup_tables($host,$user,$pass,$name,$tables = '*')
  6. {
  7.  
  8. $link = mysql_connect($host,$user,$pass);
  9. mysql_select_db($name,$link);
  10.  
  11. //get all of the tables
  12. if($tables == '*')
  13. {
  14. $tables = array();
  15. $result = mysql_query('SHOW TABLES');
  16. while($row = mysql_fetch_row($result))
  17. {
  18. $tables[] = $row[0];
  19. }
  20. }
  21. else
  22. {
  23. $tables = is_array($tables) ? $tables : explode(',',$tables);
  24. }
  25.  
  26. //cycle through
  27. foreach($tables as $table)
  28. {
  29. $result = mysql_query('SELECT * FROM '.$table);
  30. $num_fields = mysql_num_fields($result);
  31. for ($i = 0; $i < $num_fields; $i++)
  32. {
  33. $return.= 'DROP TABLE '.$table.';';
  34.  
  35. $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
  36. $return.= "\n\n".$row2[1].";\n\n";
  37.  
  38. while($row = mysql_fetch_row($result))
  39. {
  40. $return.= 'INSERT INTO '.$table.' VALUES(';
  41. for($j=0; $j<$num_fields; $j++)
  42. {
  43. $row[$j] = addslashes($row[$j]);
  44. $row[$j] = ereg_replace("\n","\\n",$row[$j]);
  45. if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
  46. if ($j<($num_fields-1)) { $return.= ','; }
  47. }
  48. $return.= ");\n";
  49. }
  50. }
  51. $return.="\n\n\n";
  52. }
  53.  
  54. //save file
  55. $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
  56. fwrite($handle,$return);
  57. fclose($handle);
  58. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.