Dump MySQL database

If you happen to have a secured server where PHP isn't allowed to do any system() calls, you have very few options to (automatically) dump your MySQL databases for backup.

I searched a while and found this little script. As I wanted to use PDO, I modified it a bit:

dbdump.php
<?php
 
define( 'DBHOST', 'db.example.org' );
define( 'DBNAME', 'mydatabase' );
define( 'DBUSER', 'mbirth' );
define( 'DBPASS', 'password' );
 
define( 'DUMPFILE', DBNAME . '.sql' );
 
header( 'Content-Type: text/plain' );
 
try {
    $db = new PDO( 'mysql:host=' . DBHOST . ';dbname=' . DBNAME, DBUSER, DBPASS );
    $f = fopen( DUMPFILE, 'wt' );
 
    $tables = $db->query( 'SHOW TABLES' );
    foreach ( $tables as $table ) {
        echo $table[0] . ' ... '; flush();
        $sql = '-- TABLE: ' . $table[0] . PHP_EOL;
        $create = $db->query( 'SHOW CREATE TABLE `' . $table[0] . '`' )->fetch();
        $sql .= $create['Create Table'] . ';' . PHP_EOL;
        fwrite( $f, $sql );
 
        $rows = $db->query( 'SELECT * FROM `' . $table[0] . '`' );
        $rows->setFetchMode( PDO::FETCH_ASSOC );
        foreach ( $rows as $row ) {
            $row = array_map( array( $db, 'quote' ), $row );
            $sql = 'INSERT INTO `' . $table[0] . '` (`' . implode( '`, `', array_keys( $row ) ) . '`) VALUES (' . implode( ', ', $row ) . ');' . PHP_EOL;
            fwrite( $f, $sql );
        }
 
        $sql = PHP_EOL;
        $result = fwrite( $f, $sql );
        if ( $result !== FALSE ) {
            echo 'OK' . PHP_EOL;
        } else {
            echo 'ERROR!!' . PHP_EOL;
        }
        flush();
    }
    fclose( $f );
} catch (Exception $e) {
    echo 'Damn it! ' . $e->getMessage() . PHP_EOL;
}
 
?>

 
snippets/php/dump-mysql-db.txt · Last modified: 2010-01-15 14:43.39 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA