Skip to content

Instantly share code, notes, and snippets.

@uxp
Created December 6, 2011 21:20
Show Gist options
  • Save uxp/1440056 to your computer and use it in GitHub Desktop.
Save uxp/1440056 to your computer and use it in GitHub Desktop.
<?php
class MySQLDumper {
/**
*
*/
private $_dbuser;
/**
*
*/
private $_dbpass;
/**
*
*/
private $_dbname;
/**
*
*/
private $_dbhost;
/**
*
*/
private $_prefix;
/**
*
*/
private $_tables;
/**
*
*/
var $link;
/**
*
*/
function __construct($host, $user, $pass, $db, $prefix = '', $tables = '*') {
if (!isset($this->_dbhost) && isset($host)) {
$this->_dbhost = $host;
}
if (!isset($this->_dbuser) && isset($user)) {
$this->_dbuser = $user;
}
if (!isset($this->_dbpass) && isset($pass)) {
$this->_dbpass = $pass;
}
if (!isset($this->_dbname) && isset($db)) {
$this->_dbname = $db;
}
if (isset($this->_prefix) || isset($prefix)) {
if (!isset($prefix)) {
$prefix = $this->_prefix;
}
if (is_array($this->_tables)) {
$tmpTables = array();
foreach ($this->_tables as $table) {
$tmpTables[] = $prefix.$table;
}
$this->_tables = $tmpTables;
} elseif (!isset($this->_tables) && isset($tables)) {
$this->_tables = $tables;
}
}
$this->link = mysql_connect($this->_dbhost, $this->_dbuser, $this->_dbpass) or die(mysql_error());
mysql_select_db($this->_dbname, $this->link);
}
/**
*
*/
function dump_database() {
if (!is_array($this->_tables)) {
$this->_tables = array();
$result = mysql_query('SHOW TABLES');
while ($row = mysql_fetch_row($result)) {
$this->_tables[] = $row[0];
}
} else {
$this->_tables = explode(',', $this->_tables);
}
$return = "\n";
$return .= "-- \n";
$return .= "-- MySQL dump script\n";
$return .= "-- Host: $this->_dbhost Database: $this->_dbname\n";
$return .= "-- ------------------------------------------------------\n";
$return .= "\n\n\n";
foreach ($this->_tables as $table) {
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return .= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return .= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysql_fetch_row($result)) {
$return .= 'INSERT INTO '.$table.' VALUES(';
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$return .= '"'.$row[$j].'"';
} else {
$return .= '""';
}
if ($j < ($num_fields - 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