Advertisement
Guest User

lv2_z1

a guest
Mar 25th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. <?php
  2.  
  3. //MySQL server and database
  4. $dbhost = 'localhost';
  5. $dbuser = 'root';
  6. $dbpass = '';
  7. $dbname = 'DB_NAME';
  8. $tables = '*';
  9.  
  10. //Call the core function
  11. backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);
  12.  
  13. //Core function
  14. function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
  15. $link = mysqli_connect($host,$user,$pass, $dbname);
  16.  
  17. // Check connection
  18. if (mysqli_connect_errno())
  19. {
  20. echo "Failed to connect to MySQL: " . mysqli_connect_error();
  21. exit;
  22. }
  23.  
  24. mysqli_query($link, "SET NAMES 'utf8'");
  25.  
  26. //get all of the tables
  27. if($tables == '*')
  28. {
  29. $tables = array();
  30. $result = mysqli_query($link, 'SHOW TABLES');
  31. while($row = mysqli_fetch_row($result))
  32. {
  33. $tables[] = $row[0];
  34. }
  35. }
  36. else
  37. {
  38. $tables = is_array($tables) ? $tables : explode(',',$tables);
  39. }
  40.  
  41. $return = '';
  42. //cycle through
  43. foreach($tables as $table)
  44. {
  45. $result = mysqli_query($link, 'SELECT * FROM '.$table);
  46. $num_fields = mysqli_num_fields($result);
  47. $num_rows = mysqli_num_rows($result);
  48.  
  49. $return.= 'DROP TABLE IF EXISTS '.$table.';';
  50. $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
  51. $return.= "\n\n".$row2[1].";\n\n";
  52. $counter = 1;
  53.  
  54. //Over tables
  55. for ($i = 0; $i < $num_fields; $i++)
  56. { //Over rows
  57. while($row = mysqli_fetch_row($result))
  58. {
  59. if($counter == 1){
  60. $return.= 'INSERT INTO '.$table.' VALUES(';
  61. } else{
  62. $return.= '(';
  63. }
  64.  
  65. //Over fields
  66. for($j=0; $j<$num_fields; $j++)
  67. {
  68. $row[$j] = addslashes($row[$j]);
  69. $row[$j] = str_replace("\n","\\n",$row[$j]);
  70. if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
  71. if ($j<($num_fields-1)) { $return.= ','; }
  72. }
  73.  
  74. if($num_rows == $counter){
  75. $return.= ");\n";
  76. } else{
  77. $return.= "),\n";
  78. }
  79. ++$counter;
  80. }
  81. }
  82. $return.="\n\n\n";
  83. }
  84.  
  85. //save file
  86. $fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.txt';
  87. $handle = fopen($fileName,'w+');
  88. fwrite($handle,$return);
  89. if(fclose($handle)){
  90. echo "Done, the file name is: ".$fileName;
  91. exit;
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement