Advertisement
DECEiFER

MySQL Backup: PHP Script - Procedural (PHP 5.5+) Syntax

Apr 29th, 2013
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.84 KB | None | 0 0
  1. <?php
  2. # MySQL Backup Script - revamped by DECEiFER (Last update: May 3rd, 2013)
  3. # Created backup files are compatible for restoration with MySQL Workbench, phpMyAdmin, etc.
  4. # -----------------
  5. # Revamped updates:
  6. # - MySQLi now used.
  7. # - Removed an unnecessary FOR loop.
  8. # - Added grave accents (``) before and after each table name to avoid MySQL reserved keyword conflicts. Queries on table names like “index” or “order” will fail without them because they are MySQL reserved keywords.
  9. # - Used DROP TABLE IF EXISTS instead of DROP TABLE.
  10. # - Added column/field names to the INSERT queries (with grave accents included).
  11. # - INSERT queries condensed – now only one query per table (phpMyAdmin formatting) – as this reduces the backup file size.
  12. # - Fixed the get tables ELSE body where the $tables variable is checked for being an array (old psuedocode: if (is array) then create an array; new psuedocode: if (is not an array) then create an array). The FOREACH loop will now always receive an array argument.
  13. # - Added an array for MySQL number types for the determination of whether a row value should be inserted to the database with quotes or not.
  14. # - Removed the "<|||||||>" delimiters as they were causing problems during restoration via phpMyAdmin and MySQL Workbench, so now the backup will be compatible with all the regular restoration methods.
  15. # - Fixes and improvements to error handling.
  16. # - Some variable names and other insignificant things changed/tidied up.
  17.  
  18. ini_set('max_execution_time', 900);
  19.  
  20. // Include your database's settings file or replace the line below with the database's credentials
  21. if (!include('config.php')) die('Cannot load the database settings.');
  22.  
  23. // List the tables you want backed up, separated by commas, or use a * for all the tables
  24. // Or list them into an array
  25. // Do not put grave accents before and after the table names - they will be formatted appropriately by the script
  26. $tables = "*";
  27.  
  28. // Set the suffix of the backup file name
  29. if ($tables == "*"){
  30.     $fileSuffix = "all";
  31. } else{
  32.     $fileSuffix = str_replace(',', '_', $tables);
  33.     $fileSuffix = str_replace(' ', '_', $fileSuffix);
  34. }
  35.  
  36. // List all the SQL numeric data types in this array
  37. // It's only necessary to put in short words (eg. int for int, smallint, bigint, etc.)
  38. $sqlNumberTypes = array('int', 'decimal', 'numeric', 'float', 'double');
  39.  
  40. // Call the backup function
  41. backup_tables($DBhost, $DBuser, $DBpass, $DBName, $tables, $fileSuffix, $sqlNumberTypes);
  42.  
  43. // Backup the tables and save them to an SQL file
  44. function backup_tables($host, $user, $pass, $name, $tables, $fileSuffix, $sqlNumberTypes){
  45.     // Open the MySQL connection and select the appropriate database
  46.     $link = mysqli_connect($host, $user, $pass) or die(mysqli_connect_error());
  47.     if ($link) mysqli_select_db($link, $name) or die(mysqli_error($link));
  48.     $output = "";
  49.    
  50.     // Get all of the tables
  51.     if ($tables == "*"){
  52.         $tables = array();
  53.         $result = mysqli_query($link, 'SHOW TABLES');
  54.         while($row = mysqli_fetch_row($result)){
  55.             $tables[] = $row[0];
  56.         }
  57.     } elseif (!is_array($tables)){
  58.         $tables = explode(',', trim($tables));
  59.     }
  60.    
  61.     // Cycle through each provided table
  62.     foreach ($tables as $table){
  63.         $table = str_replace('`', '', $table);
  64.        
  65.         $result = mysqli_query($link, 'SELECT * FROM `' . $table . '`');
  66.         $num_fields = ($result) ? mysqli_num_fields($result) : 0;
  67.         $num_rows = ($num_fields > 0 && $result) ? mysqli_num_rows($result) : 0;
  68.        
  69.         // Put all of the table's columns into a SQL-formatted string and push each column type into an array
  70.         $cols = "";
  71.         $colsArray = array();
  72.         $colsType = array();
  73.         $res = mysqli_query($link, 'SHOW COLUMNS FROM `' . $table . '`');
  74.         while ($col = mysqli_fetch_row($res)){
  75.             $colsArray[] = $col[0];
  76.             $colsType[] = $col[1];
  77.         }
  78.         $sizeOf = sizeof($colsArray);
  79.         foreach ($colsArray as $key => $col){
  80.             $cols .= "`" . $col . "`";
  81.             if ($key < ($sizeOf - 1)) $cols .= ", ";
  82.         }
  83.        
  84.         // First part of the output – remove the table
  85.         $output .= "DROP TABLE IF EXISTS `" . $table . "`;";
  86.        
  87.         // Second part of the output – create table
  88.         $row = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE `' . $table . '`'));
  89.         $output .= $row[1] . ";\n\n";
  90.        
  91.         // Third part of the output – insert values into new table
  92.         $i = 0;
  93.         if ($num_rows > 0) $output .= "INSERT INTO `" . $table . "` (" . $cols . ") VALUES ";
  94.         while ($row = mysqli_fetch_row($result)){
  95.             $output .= "(";
  96.             for ($j = 0; $j < $num_fields; $j++) {
  97.                 $row[$j] = mysqli_real_escape_string($link, $row[$j]);
  98.                 if (isset($row[$j])){
  99.                     $output .= (striposa($colsType[$j], $sqlNumberTypes) === false) ? "'" . $row[$j] . "'" : $row[$j];
  100.                 } else{
  101.                     $output .= (striposa($colsType[$j], $sqlNumberTypes) === false) ? "''" : "NULL";
  102.                 }
  103.                 if ($j < ($num_fields - 1)){
  104.                     $output .= ", ";
  105.                 }
  106.             }
  107.             $output .= ($i < ($num_rows - 1)) ? "),\n" : ");";
  108.             $i++;
  109.         }
  110.         $output .= "\n\n\n";
  111.     }
  112.    
  113.     // Close the MySQL Connection
  114.     mysqli_close($link);
  115.    
  116.     // Generate the filename for the sql file
  117.     $backupFile = $name . "_" .date('d.m.Y_H.i.s') . '_' . $fileSuffix . '.sql';
  118.    
  119.     // Save the SQL file
  120.     $handle = fopen($backupFile, 'a') or die('Cannot create file.');
  121.     if ($handle){
  122.         fwrite($handle, $output);
  123.         fclose($handle);
  124.     }
  125.    
  126.     // Echo the success message
  127.     echo "The backup has been created successfully. You can get the file <a href=\"" . $backupFile . "\">here</a>.<br />\n";
  128. }
  129.  
  130. // Returns the first index of an array of string search term values based on a character offset defaulting to 0 (false on failure)
  131. // Only the lowest index from the search term values will returned
  132. function striposa($haystack, $needles = array(), $offset = 0){
  133.     $chr = array();
  134.     foreach($needles as $needle) {
  135.         if (($pos = stripos($haystack, $needle, $offset)) !== false) $chr[] = $pos;
  136.     }
  137.     if(empty($chr)) return false;
  138.     return min($chr);
  139. }
  140. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement