Created
September 26, 2012 10:16
-
-
Save jkaflik/3787188 to your computer and use it in GitHub Desktop.
Simple MySQL database dump lib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Dump | |
{ | |
public static function from( $host, $username, $password, $database, $charset = 'utf8' ) | |
{ | |
$o = new self; | |
$o->host = $host; | |
$o->username = $username; | |
$o->password = $password; | |
$o->database = $database; | |
$o->charset = $charset; | |
return $o; | |
} | |
public $host; | |
public $username; | |
public $password; | |
public $database; | |
public $charset; | |
public function save( $filename ) | |
{ | |
if( file_exists( $filename ) ) | |
{ | |
throw new Exception('File arleady exists.'); | |
} | |
$file = new SplFileObject( $filename, 'w' );//fopen( $filename, 'w' ); | |
$mysql = mysql_connect( $this->host, $this->username, $this->password ); | |
mysql_select_db( $this->database, $mysql ); | |
mysql_set_charset( $this->charset, $mysql ); | |
$tables = array(); | |
$result = mysql_query('SHOW TABLES'); | |
while( $row = mysql_fetch_row( $result ) ) | |
{ | |
$tables[] = $row[0]; | |
} | |
foreach( $tables as $table ) | |
{ | |
$result = mysql_fetch_row( mysql_query("SHOW CREATE TABLE $table;") ); | |
$file->fwrite( "DROP TABLE IF EXISTS $table;" . PHP_EOL . PHP_EOL ); | |
$file->fwrite( $result[1] . ";" . PHP_EOL . PHP_EOL ); | |
$offset = 0; | |
while( true ) | |
{ | |
$result = mysql_query("SELECT * FROM $table LIMIT $offset, 50;"); | |
$count = mysql_num_rows( $result ); | |
while( $row = mysql_fetch_row($result) ) | |
{ | |
$file->fwrite("INSERT INTO $table VALUES("); | |
foreach( $row as $k => $v ) | |
{ | |
$v = str_replace("\n", "\\n", addslashes( $v )); | |
$file->fwrite("'$v'"); | |
if( $k < count($row)-1 ) $file->fwrite(','); | |
} | |
$file->fwrite(");" . PHP_EOL); | |
} | |
if( $count < 50 ) break; | |
$offset += 50; | |
} | |
$file->fwrite(PHP_EOL . PHP_EOL); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment