Backup MySQL Database Using PHP

This code will help you on how to backup your database. I Created this code to help thus programmer that encountered difficulties in creating backup of their database. The features of this code is that it allows you to backup your MySQL database. In this this code also you will learn on how to get all list of file in a folder directory. I hope this code will help you, if you have some question of this code, please throw us some question.

Backup MySQL Database Using PHP

Import and export of data to and from any database is a common task of any website development. By exporting databases we secured our application from any kind of data loss. Sometimes, we need to develop our own custom PHP code to import or export databases. So friends, in this tutorial, I will show you how to backup or export MySQL database using PHP.

 

Backup or Export MySQL Database Using PHP

By using this PHP code you can export the whole database at once or you can export specific tables. Mention the specific table names that you want to download – $tables = array(“table1”, “table2”, “table3”, …);  Please follow the below code —

  1. define("DB_HOST", "localhost");
  2. define("DB_USERNAME", "username");
  3. define("DB_PASSWORD", "password");
  4. define("DB_NAME", "database_name");
  5.  
  6. $con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("Error : ");
  7. if(mysqli_connect_errno($con)) {
  8. echo "Failed to connect MySQL: " .mysqli_connect_error();
  9. } else {
  10. //If you want to export or backup the whole database then leave the $table variable as it is
  11. //If you want to export or backup few table then mention the names of the tables within the $table array like below
  12. //eg, $tables = array("wp_commentmeta", "wp_comments", "wp_options");
  13.  
  14. $tables = array();
  15. $backup_file_name = DB_NAME.".sql";
  16. backup_database($con, $tables, $backup_file_name);
  17. }
  18. ?>
  19.  
  20. function backup_database($con, $tables = "", $backup_file_name) {
  21.  
  22. if(empty($tables)) {
  23. $tables_in_database = mysqli_query($con, "SHOW TABLES");
  24. if(mysqli_num_rows($tables_in_database) > 0) {
  25. while($row = mysqli_fetch_row($tables_in_database)) {
  26. array_push($tables, $row[0]);
  27. }
  28. }
  29. } else {
  30. // Checking for any table that doesn't exists in the database
  31. $existed_tables = array();
  32. foreach($tables as $table) {
  33. if(mysqli_num_rows(mysqli_query($con, "SHOW TABLES LIKE '".$table."'")) == 1) {
  34. array_push($existed_tables, $table);
  35. }
  36. }
  37. $tables = $existed_tables;
  38. }
  39.  
  40.  
  41. $contents = "--\n-- Database: `".DB_NAME."`\n--\n-- --------------------------------------------------------\n\n\n\n";
  42.  
  43. foreach($tables as $table) {
  44. $result = mysqli_query($con, "SELECT * FROM ".$table);
  45. $no_of_columns = mysqli_num_fields($result);
  46. $no_of_rows = mysqli_num_rows($result);
  47.  
  48. //Get the query for table creation
  49. $table_query = mysqli_query($con, "SHOW CREATE TABLE ".$table);
  50. $table_query_res = mysqli_fetch_row($table_query);
  51.  
  52. $contents .= "--\n-- Table structure for table `".$table."`\n--\n\n";
  53. $contents .= $table_query_res[1].";\n\n\n\n";
  54.  
  55. /**
  56. * $insert_limit -> Limits the number of row insertion in a single INSERT query.
  57. * Maximum 100 rowswe will insert in a single INSERT query.
  58. * $insert_count -> Counts the number of rows are added to the INSERT query.
  59. * When it will reach the insert limit it will set to 0 again.
  60. * $total_count -> Counts the overall number of rows are added to the INSERT query of a single table.
  61. */
  62. $insert_limit = 100;
  63. $insert_count = 0;
  64. $total_count = 0;
  65.  
  66.  
  67. while($result_row = mysqli_fetch_row($result)) {
  68.  
  69. /**
  70. * For the first time when $insert_count is 0 and when $insert_count reached the $insert_limit
  71. * and again set to 0 this if condition will execute and append the INSERT query in the sql file.
  72. */
  73. if($insert_count == 0) {
  74. $contents .= "--\n-- Dumping data for table `".$table."`\n--\n\n";
  75. $contents .= "INSERT INTO ".$table." VALUES ";
  76. }
  77.  
  78. //Values part of an INSERT query will start from here eg. ("1","mitrajit","India"),
  79. $insert_query = "";
  80. $contents .= "\n(";
  81. for($j=0; $j<$no_of_columns; $j++) {
  82. //Replace any "\n" with "\\n" escape character.
  83. //addslashes() function adds escape character to any double quote or single quote eg, \" or \'
  84. $insert_query .= "'".str_replace("\n","\\n", addslashes($result_row[$j]))."',";
  85. }
  86. //Remove the last unwanted comma (,) from the query.
  87. $insert_query = substr($insert_query, 0, -1)."),";
  88.  
  89. /*
  90. * If $insert_count reached to the insert limit of a single INSERT query
  91. * or $insert count reached to the number of total rows of a table
  92. * or overall total count reached to the number of total rows of a table
  93. * this if condition will exceute.
  94. */
  95. if($insert_count == ($insert_limit-1) || $insert_count == ($no_of_rows-1) || $total_count == ($no_of_rows-1)) {
  96. //Remove the last unwanted comma (,) from the query and append a semicolon (;) to it
  97. $contents .= substr($insert_query, 0, -1);
  98. $contents .= ";\n\n\n\n";
  99. $insert_count = 0;
  100. } else {
  101. $contents .= $insert_query;
  102. $insert_count++;
  103. }
  104.  
  105. $total_count++;
  106. }
  107. }
  108.  
  109.  
  110. //Set the HTTP header of the page.
  111. header('Content-Type: application/octet-stream');
  112. header("Content-Transfer-Encoding: Binary");
  113. header("Content-disposition: attachment; filename=\"".$backup_file_name."\"");
  114. echo $contents; exit;
  115. }
  116. ?>

The PHP array_push() function adds elements into an array and the addslashes() function quote string with slashes. The substr() function returns a part of the string.

Change the Database host, name, username, and password according to your database credentials. Except for these changes, you do not need to do anything. Just run the code and backup or export the MySQL database to your system.

That’s all friends, Hope you enjoyed this tutorial. If you face any problem feel free to inform me in the comment section below. Please like and share this tutorial on how to backup or export MySQL database using PHP with others. Kindly subscribe F5CRAFT to keep yourself updated with the upcoming tutorials.

Need a Website Or Web Application Or Any Help In Code , Contact Us: +91 8778409644 (Whatsapp) or Email: uma@f5craft.com | Visit: www.f5craft.in /.com, Note: Paid Service Only