Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DatabaseDump {
- private $db;
- private $host, $user, $pass, $dbname;
- private $sql, $removeAI;
- public function __construct($host, $user, $pass, $dbname) {
- $this->host = $host;
- $this->user = $user;
- $this->pass = $pass;
- $this->dbname = $dbname;
- $this->removeAI = true;
- try {
- $this->db = new PDO('mysql:dbname='.$dbname.';host='.$host, $user, $pass);
- $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- } catch(PDOException $e) {
- echo 'Connection failed: ' . $e->getMessage();
- die;
- }
- }
- private function ln($text = '') {
- $this->sql = $this->sql . $text . "\n";
- }
- public function getInsert($table) {
- $output = "";
- $fields = "";
- $sep2 = "";
- $stmt = $this->db->query("SELECT * FROM $table");
- while($row = $stmt->fetch(PDO::FETCH_OBJ)){
- // runs once per table - create the INSERT INTO clause
- if($fields == ""){
- $fields = "INSERT INTO `$table` (";
- $sep = "";
- // grab each field name
- foreach($row as $col => $val){
- $fields .= $sep . "`$col`";
- $sep = ", ";
- }
- $fields .= ") VALUES";
- $output .= $fields . "\n";
- }
- // grab table data
- $sep = "";
- $output .= $sep2 . "(";
- foreach($row as $col => $val){
- // add slashes to field content
- $val = addslashes($val);
- // replace stuff that needs replacing
- //$val = str_replace($search, $replace, $val);
- $output .= $sep . "'$val'";
- $sep = ", ";
- }
- // terminate row data
- $output .= ")";
- $sep2 = ",\n";
- }
- // terminate insert data
- $output .= ";\n";
- return $output;
- }
- public function dump($file) {
- $this->ln("SET FOREIGN_KEY_CHECKS=0;\n");
- $tables = $this->db->query('SHOW TABLES')->fetchAll(PDO::FETCH_BOTH);
- foreach ($tables as $table) {
- $table = $table[0];
- $this->ln('DROP TABLE IF EXISTS `'.$table.'`;');
- $schemas = $this->db->query("SHOW CREATE TABLE `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
- foreach ($schemas as $schema) {
- $schema = $schema['Create Table'];
- if($this->removeAI) $schema = preg_replace('/AUTO_INCREMENT=([0-9]+)(\s{0,1})/', '', $schema);
- $this->ln($schema.";\n\n");
- $insertSql = $this->getInsert($table);
- $this->ln($insertSql);
- }
- }
- file_put_contents($file, $this->sql);
- }
- }
- $host = 'localhost';
- $user = 'root';
- $pass = '';
- $dbname = 'database';
- $date = date('Y-m-d-H-i');
- $filename = "dump.{$date}.sql";
- $dbDump = new DatabaseDump($host, $user, $pass, $dbname);
- $dbDump->dump($filename);
- exit(sprintf('<a href="%s" target="_blank">Download file</a>', $filename));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement