Backup Your MySQL Database Using PHP


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

Database backup function that you can call whenever you want — including nightly CRONs.


Copy this code and paste it in your HTML
  1. <?php
  2. backup_tables('localhost','misslily','misslily','blog','*');
  3.  
  4.  
  5. /* backup the db OR just a table */
  6. function backup_tables($host,$user,$pass,$name,$tables = '*'){
  7. $return = "";
  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.  
  32. $return.= 'DROP TABLE '.$table.';';
  33. $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
  34. $return.= "\n\n".$row2[1].";\n\n";
  35.  
  36. for ($i = 0; $i < $num_fields; $i++)
  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. }
  59. ?>

URL: http://davidwalsh.name/backup-mysql-database-php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.