ekasyahwan

Dump PHP

May 9th, 2014
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. <?php
  2. // db config
  3. $dbhost = 'localhost';
  4. $dbuser = 'dbuser';
  5. $dbpass = 'dbpassword';
  6. $dbname = 'dbname';
  7. // db connect
  8. $pdo = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
  9. // file header stuff
  10. $output = "-- PHP MySQL Dump\n--\n";
  11. $output .= "-- Host: $dbhost\n";
  12. $output .= "-- Generated: " . date("r", time()) . "\n";
  13. $output .= "-- PHP Version: " . phpversion() . "\n\n";
  14. $output .= "SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n\n";
  15. $output .= "--\n-- Database: `$dbname`\n--\n";
  16. // get all table names in db and stuff them into an array
  17. $tables = array();
  18. $stmt = $pdo->query("SHOW TABLES");
  19. while($row = $stmt->fetch(PDO::FETCH_NUM)){
  20. $tables[] = $row[0];
  21. }
  22. // process each table in the db
  23. foreach($tables as $table){
  24. $fields = "";
  25. $sep2 = "";
  26. $output .= "\n-- " . str_repeat("-", 60) . "\n\n";
  27. $output .= "--\n-- Table structure for table `$table`\n--\n\n";
  28. // get table create info
  29. $stmt = $pdo->query("SHOW CREATE TABLE $table");
  30. $row = $stmt->fetch(PDO::FETCH_NUM);
  31. $output.= $row[1].";\n\n";
  32. // get table data
  33. $output .= "--\n-- Dumping data for table `$table`\n--\n\n";
  34. $stmt = $pdo->query("SELECT * FROM $table");
  35. while($row = $stmt->fetch(PDO::FETCH_OBJ)){
  36. // runs once per table - create the INSERT INTO clause
  37. if($fields == ""){
  38. $fields = "INSERT INTO `$table` (";
  39. $sep = "";
  40. // grab each field name
  41. foreach($row as $col => $val){
  42. $fields .= $sep . "`$col`";
  43. $sep = ", ";
  44. }
  45. $fields .= ") VALUES";
  46. $output .= $fields . "\n";
  47. }
  48. // grab table data
  49. $sep = "";
  50. $output .= $sep2 . "(";
  51. foreach($row as $col => $val){
  52. // add slashes to field content
  53. $val = addslashes($val);
  54. // replace stuff that needs replacing
  55. $search = array("\'", "\n", "\r");
  56. $replace = array("''", "\\n", "\\r");
  57. $val = str_replace($search, $replace, $val);
  58. $output .= $sep . "'$val'";
  59. $sep = ", ";
  60. }
  61. // terminate row data
  62. $output .= ")";
  63. $sep2 = ",\n";
  64. }
  65. // terminate insert data
  66. $output .= ";\n";
  67. }
  68. // output file to browser
  69. header('Content-Description: File Transfer');
  70. header('Content-type: application/octet-stream');
  71. header('Content-Disposition: attachment; filename=' . $dbname . '.sql');
  72. header('Content-Transfer-Encoding: binary');
  73. header('Content-Length: ' . strlen($output));
  74. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  75. header('Expires: 0');
  76. header('Pragma: public');
  77. echo $output;
  78. ?>
Add Comment
Please, Sign In to add comment