Skip to content

Instantly share code, notes, and snippets.

@WolfgangDrescher
Created July 30, 2014 21:31
Show Gist options
  • Save WolfgangDrescher/30043fa6dcbded6d3f3f to your computer and use it in GitHub Desktop.
Save WolfgangDrescher/30043fa6dcbded6d3f3f to your computer and use it in GitHub Desktop.
Static method DBi::backup() that returns the complete database
<?php
class DBi {
// ...
static function backup($tables = '*') {
if($tables == '*') {
$tables = array();
$get = new Query('SHOW TABLES');
while($row = $get->fetchRow()) {
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$return = '';
foreach($tables as $table) {
$get = new Query('SELECT * FROM ' . $table);
$field_count = $get->getResult()->field_count;
// $return .= 'DROP TABLE ' . $table . ';';
$get2 = new Query('SHOW CREATE TABLE ' . $table); // CREATE TABLE IF NOT EXISTS
$row2 = $get2->fetchArray();
$return .= "\n\n" . $row2[1] . ";\n\n";
for($i = 0; $i < $field_count; $i++) {
while($row = $get->fetchRow()) {
$return .= 'INSERT INTO ' . $table . ' VALUES (';
for($j = 0; $j < $field_count; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", "\\n", $row[$j]);
if(isset($row[$j])) {
$return .= '"' . $row[$j] . '"' ;
} else {
$return .= '""';
}
if($j < ($field_count - 1)) {
$return .= ', ';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
return $return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment