kwasinski

Database Dumper Class (Not Finished)

Mar 24th, 2016
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.11 KB | None | 0 0
  1. <?php
  2. $dumperObject = new DbDumper();
  3. $dumperObject->magic();
  4. $dumperObject->init([
  5.     'host' => 'localhost',
  6.     'port' => '3306',
  7.     'dbname' => 'mg_bazarsports',
  8.     'user' => '#######',
  9.     'password' => '######',
  10. ]);
  11.  
  12. $dumperObject->debug();
  13.  
  14.  
  15. /*
  16. *   Author vkwasinski at gmail or vinicius.carvalho at agenciafrog.com.br
  17. *
  18. *   This class is intent to dump databases
  19. *   which not have foreign host access enable
  20. *
  21. *   USAGE:
  22. *
  23. *   $dumperObject = new DbDumper([
  24. *       'host' => 'localhost',
  25. *       'port' => '3306',
  26. *       'dbname' => 'ventura_wp',
  27. *       'user' => 'root',
  28. *       'password' => '',
  29. *   ]);
  30. *
  31. *  Will dump the whole database to a file and download it for you as [dbname]_dump.sql :')
  32. *
  33. */
  34.  
  35. class DbDumper {
  36.  
  37.     private $context = [];
  38.     private $connectionString = "mysql:host=#host;port=#port;dbname=#dbname";
  39.     private $connectionContext = [
  40.         'host' => NULL,
  41.         'port' => NULL,
  42.         'dbname' => NULL,
  43.         'user' => NULL,
  44.         'password' => NULL,
  45.     ];
  46.     var $error = [];
  47.  
  48.     // Search in the context and then in the connectionContext
  49.     public function __get($name) {
  50.         if (isset($this->context[$name]) && !is_null($this->context[$name])) {
  51.             return $this->context[$name];
  52.  
  53.         } else if (isset($this->connectionContext[$name]) && !is_null($this->connectionContext[$name])) {
  54.             return $this->connectionContext[$name];
  55.         }
  56.     }
  57.  
  58.     public function __set($name, $value) { isset($value) && !is_null($value)? $this->context[$name] = $value: NULL; }
  59.     public function __call($method, $arguments) { $this->__behavioral(); return $this;}
  60.     public function __wakeup() { $connection->reconnect(); }
  61.     public function __toString() { return ''.$this; }
  62.     public function __behavioral() {
  63.         // print '<pre>';
  64.         return $this;
  65.     } // This method is defined to change the object behavior after each method called
  66.  
  67.     public function __construct($arrCredentials = false) {
  68.         $this->init($arrCredentials);
  69.         return $this;
  70.     }
  71.  
  72.     public function init($arrCredentials = false) {
  73.         if (!$arrCredentials)  return false;
  74.  
  75.         foreach (array_keys($this->connectionContext) as $expectedKey) {
  76.             if (!isset($arrCredentials[$expectedKey])) {
  77.                 $this->error[] = "$expectedKey missing";
  78.                 continue;
  79.             }
  80.  
  81.             $this->connectionContext[$expectedKey] = $arrCredentials[$expectedKey];
  82.         }
  83.  
  84.         if (empty($this->error)) try {
  85.             $this->setCredentials(); // set connection credentials to the actual database;
  86.             $this->setConnection(); // Instance of a new PDO
  87.             $this->showTables(); // SHOW TABLES;
  88.             $this->appendFileHeader();
  89.             $this->dumpData(); // Come along every table and create insert statements
  90.             // $this->createDumpFile();
  91.         } catch (PDOException $e) {
  92.             $this->error[] = 'Error!: '.$e->getMessage();
  93.             die(implode(', ',$this->error));
  94.         }
  95.  
  96.         return $this;
  97.     }
  98.  
  99.     private function setCredentials() {
  100.         if (!empty($this->error))  return $this;
  101.         foreach (array_keys($this->connectionContext) as $connectionParam)
  102.             $this->connectionString = preg_replace("/\#$connectionParam/", $this->connectionContext[$connectionParam], $this->connectionString);
  103.  
  104.         return $this;
  105.     }
  106.  
  107.     public function setConnection() {
  108.         if (!empty($this->error))  return $this;
  109.         $this->connection = new PDO($this->connectionString, $this->user, $this->password);
  110.         return $this;
  111.     }
  112.  
  113.     public function showTables() {
  114.         if (!empty($this->error))  return $this;
  115.         $this->tablesToparse = $this->query('SHOW TABLES;');
  116.         return $this;
  117.     }
  118.  
  119.     private function appendFileHeader() {
  120.         if (!empty($this->error))  return $this;
  121.  
  122.         $this->file .= "CREATE DATABASE IF NOT EXISTS `{$this->dbname}`;\n\n";
  123.         $this->file .= "USE `{$this->dbname}`;\n\n";
  124.         $this->file .= "SET character_set_client = utf8;\n\n";
  125.  
  126.         return $this;
  127.     }
  128.  
  129.     public function dumpData() {
  130.         if (!empty($this->error))  return $this;
  131.  
  132.         $this->tablesStrutures = [];
  133.         foreach ( $this->tablesToparse as $tableName) {
  134.             $tableName = $tableName{'Tables_in_'.$this->dbname};
  135.  
  136.             $this->appendCreateTable($tableName);
  137.             $this->appendInserts($tableName);
  138.         }
  139.  
  140.         // var_dump($this->file);
  141.     }
  142.  
  143.     private function appendCreateTable($tableName) {
  144.         if (!$tableName)  return;
  145.  
  146.         $createTableStatement = $this->query("SHOW CREATE TABLE $tableName;")[0];
  147.         $createTableStatement['Create Table'];
  148.         $this->file .= "DROP TABLE IF EXISTS `$tableName`;\n";
  149.         $this->file .= $createTableStatement['Create Table'].";\n\n";
  150.     }
  151.  
  152.     private function appendInserts($tableName) {
  153.         if (!($tableName && empty($this->error)))  return;
  154.  
  155.         $this->file .= "LOCK TABLES `$tableName` WRITE;\n";
  156.  
  157.         // We must read the table columns metadata
  158.         // to know about the type of the column and generate the right INSERT statement
  159.         // We can instead of just passing the table's name to this function
  160.         // pass a associative array like [column_name => column_type],
  161.         // perhaps we just need to differ string from integer and treat NULL and Empty strings.
  162.         $wholeTable = $this->query("SELECT * FROM wp_posts;");
  163.         print '<pre>';
  164.         var_dump($wholeTable);
  165.  
  166.         exit;
  167.         $this->file .= "UNLOCK TABLES;\n\n";
  168.     }
  169.  
  170.     private function query($statement) {
  171.         if (!($statement && empty($this->error)))  return;
  172.         try {
  173.             $query = $this->connection->prepare($statement);
  174.             $query->execute();
  175.             $query = $query->fetchAll(PDO::FETCH_ASSOC);
  176.  
  177.         } catch (PDOException $e) {
  178.             $this->error[] = 'Error!: '.$e->getMessage();
  179.         }
  180.  
  181.         return $query;
  182.     }
  183.  
  184.     // This method is intent to create a SQLDump File from the flagged Database
  185.     public function createDumpFile() {
  186.         if (!empty($this->error))  return $this;
  187.  
  188.         $this->filename = $this->dbname.'_dump.sql';
  189.         file_put_contents($this->filename, $this->file);
  190.  
  191.         return;
  192.  
  193.         header('Content-Description: File Transfer');
  194.         header('Content-type: application/octet-stream');
  195.         header('Content-Disposition: attachment; filename='.$this->filename);
  196.         header('Content-Transfer-Encoding: binary');
  197.         header('Content-Length: ' . strlen($this->file));
  198.         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  199.         header('Expires: 0');
  200.         header('Pragma: public');
  201.  
  202.         print $this->file;
  203.  
  204.         return $this;
  205.     }
  206.  
  207.     public function debug() {
  208.         print '<pre>';
  209.         var_dump($this);
  210.         print '</pre>';
  211.     }
  212.  
  213.  
  214. }
Add Comment
Please, Sign In to add comment