PHP Source Code for backing up Database

http://reeteshghimire.com.np/2019/07/04/backup-restore-mysql-database-using-php/

https://stackoverflow.com/questions/22195493/export-mysql-database-using-php-only

  1. <?php
  2. $connection = mysqli_connect('localhost','root','','quiz');
  3. $tables = array();
  4. $result = mysqli_query($connection,"SHOW TABLES");
  5. while($row = mysqli_fetch_row($result)){
  6. $tables[] = $row[0];
  7. }
  8. $return = '';
  9. foreach($tables as $table){
  10. $result = mysqli_query($connection,"SELECT * FROM ".$table);
  11. $num_fields = mysqli_num_fields($result);
  12. $return .= 'DROP TABLE '.$table.';';
  13. $row2 = mysqli_fetch_row(mysqli_query($connection,"SHOW CREATE TABLE ".$table));
  14. $return .= "\n\n".$row2[1].";\n\n";
  15. for($i=0;$i<$num_fields;$i++){
  16. while($row = mysqli_fetch_row($result)){
  17. $return .= "INSERT INTO ".$table." VALUES(";
  18. for($j=0;$j<$num_fields;$j++){
  19. $row[$j] = addslashes($row[$j]);
  20. if(isset($row[$j])){ $return .= '"'.$row[$j].'"';}
  21. else{ $return .= '""';}
  22. if($j<$num_fields-1){ $return .= ',';}
  23. }
  24. $return .= ");\n";
  25. }
  26. }
  27. $return .= "\n\n\n";
  28. }
  29. //save file
  30. $handle = fopen("backup.sql","w+");
  31. fwrite($handle,$return);
  32. fclose($handle);
  33. echo "Successfully backed up";

Source Code for Restoring the Database

  1. <?php
  2. $connection = mysqli_connect('localhost','root','','test');
  3. $filename = 'backup.sql';
  4. $handle = fopen($filename,"r+");
  5. $contents = fread($handle,filesize($filename));
  6. $sql = explode(';',$contents);
  7. foreach($sql as $query){
  8. $result = mysqli_query($connection,$query);
  9. if($result){
  10. echo '<tr><td><br></td></tr>';
  11. echo '<tr><td>'.$query.' <b>SUCCESS</b></td></tr>';
  12. echo '<tr><td><br></td></tr>';
  13. }
  14. }
  15. fclose($handle);
  16. echo 'Successfully imported';

Comments

Popular posts from this blog

Create a RESTful API using PHP, My-sql and Slim-Framework

DeltaPi softwares

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)