Skip to main content

Backup (or) Download MYSQL Database as a zip file Using PHP

NOTE:Please change below credentials  with respect to your Database and Run the file.

<?php

define("DB_USER"'DatabaseUSERNAME');define("DB_PASSWORD"'DatabasePASSWORD');define("DB_NAME"'DatabaseNAME');define("DB_HOST"'localhost');define("BACKUP_DIR"'myphp-backup-files'); // Comment this line to use same script's directory ('.')define("TABLES"'*'); // Full backup
//define("TABLES", 'table1, table2, table3'); // Partial backup of required tablesdefine("CHARSET"'utf8');define("GZIP_BACKUP_FILE"true);  // Set to false if you want plain SQL backup files (not gzipped)
class Backup_Database{
    var $host;
    var $username;
    var $passwd;
    var $dbName;
    var $charset;
    var $conn;
    var $backupDir;
    var $backupFile;
    var $gzipBackupFile;
    public function __construct($host$username$passwd$dbName$charset 'utf8')
    {
        $this->host            $host;
        $this->username        $username;
        $this->passwd          $passwd;
        $this->dbName          $dbName;
        $this->charset         $charset;
        $this->conn            $this->initializeDatabase();
        $this->backupDir       BACKUP_DIR BACKUP_DIR '.';
        $this->backupFile      'myphp-backup-'.$this->dbName.'-'.date("Ymd_His"time()).'.sql';
        $this->gzipBackupFile  defined('GZIP_BACKUP_FILE') ? GZIP_BACKUP_FILE true;
    }
    protected function initializeDatabase()
    {
        try
        {
            $conn mysqli_connect($this->host$this->username$this->passwd$this->dbName);
            if (mysqli_connect_errno())
            {
                throw new Exception('ERROR connecting database: ' mysqli_connect_error());
                die();
            }
            if (!mysqli_set_charset($conn$this->charset))
            {
                mysqli_query($conn'SET NAMES '.$this->charset);
            }
        }
        catch (Exception $e)
        {
            print_r($e->getMessage());
            die();
        }
        return $conn;
    }
    /**
     * Backup the whole database or just some tables
     * Use '*' for whole database or 'table1 table2 table3...'
     * @param string $tables
     */
    public function backupTables($tables '*') {
        try {
            /**
             * Tables to export
             */
            if($tables == '*') {
                $tables = array();
                $result mysqli_query($this->conn'SHOW TABLES');
                while($row mysqli_fetch_row($result)) {
                    $tables[] = $row[0];
                }
            } else {
                $tables is_array($tables) ? $tables explode(','str_replace(' '''$tables));
            }
            $sql 'CREATE DATABASE IF NOT EXISTS `'.$this->dbName."`;\n\n";
            $sql .= 'USE '.$this->dbName.";\n\n";
            /**
             * Iterate tables
             */
            foreach($tables as $table) {
                $this->obfPrint("Backing up `".$table."` table...".str_repeat('.'50-strlen($table)), 00);
                /**
                 * CREATE TABLE
                 */
                $sql .= 'DROP TABLE IF EXISTS `'.$table.'`;';
                $row mysqli_fetch_row(mysqli_query($this->conn'SHOW CREATE TABLE `'.$table.'`'));
                $sql .= "\n\n".$row[1].";\n\n";
                /**
                 * INSERT INTO
                 */
                $row mysqli_fetch_row(mysqli_query($this->conn'SELECT COUNT(*) FROM `'.$table.'`'));
                $numRows $row[0];
                // Split table in batches in order to not exhaust system memory
                $batchSize 1000// Number of rows per batch
                $numBatches intval($numRows $batchSize) + 1// Number of while-loop calls to perform
                for ($b 1$b <= $numBatches$b++) {

                    $query 'SELECT * FROM `'.$table.'` LIMIT '.($b*$batchSize-$batchSize).','.$batchSize;
                    $result mysqli_query($this->conn$query);
                    $numFields mysqli_num_fields($result);
                    for ($i 0$i $numFields$i++) {
                        $rowCount 0;
                        while($row mysqli_fetch_row($result)) {
                            $sql .= 'INSERT INTO `'.$table.'` VALUES(';
                            for($j=0$j<$numFields$j++) {
                                if (isset($row[$j])) {
                                    $row[$j] = addslashes($row[$j]);
                                    $row[$j] = str_replace("\n","\\n",$row[$j]);
                                    $sql .= '"'.$row[$j].'"' ;
                                } else {
                                    $sql.= 'NULL';
                                }
                                if ($j < ($numFields-1)) {
                                    $sql .= ',';
                                }
                            }
                            $sql.= ");\n";
                        }
                    }
                    $this->saveFile($sql);
                    $sql '';
                }
                $sql.="\n\n\n";
                $this->obfPrint(" OK");
            }
            if ($this->gzipBackupFile) {
                $this->gzipBackupFile();
            } else {
                $this->obfPrint('Backup file succesfully saved to ' $this->backupDir.'/'.$this->backupFile11);
            }
        } catch (Exception $e) {
            print_r($e->getMessage());
            return false;
        }
        return true;
    }
    /**
     * Save SQL to file
     * @param string $sql
     */
    protected function saveFile(&$sql) {
        if (!$sql) return false;
        try {
            if (!file_exists($this->backupDir)) {
                mkdir($this->backupDir0777true);
            }
            file_put_contents($this->backupDir.'/'.$this->backupFile$sqlFILE_APPEND LOCK_EX);
        } catch (Exception $e) {
            print_r($e->getMessage());
            return false;
        }
        return true;
    }
    /*
     * Gzip backup file
     *
     * @param integer $level GZIP compression level (default: 9)
     * @return string New filename (with .gz appended) if success, or false if operation fails
     */
    protected function gzipBackupFile($level 9) {
        if (!$this->gzipBackupFile) {
            return true;
        }
        $source $this->backupDir '/' $this->backupFile;
        $dest =  $source '.gz';
        $this->obfPrint('Gzipping backup file to ' $dest '... '10);
        $mode 'wb' $level;
        if ($fpOut gzopen($dest$mode)) {
            if ($fpIn fopen($source,'rb')) {
                while (!feof($fpIn)) {
                    gzwrite($fpOutfread($fpIn1024 256));
                }
                fclose($fpIn);
            } else {
                return false;
            }
            gzclose($fpOut);
            if(!unlink($source)) {
                return false;
            }
        } else {
            return false;
        }

        $this->obfPrint('OK');
        return $dest;
    }
    /**
     * Prints message forcing output buffer flush
     *
     */
    public function obfPrint ($msg ''$lineBreaksBefore 0$lineBreaksAfter 1) {
        if (!$msg) {
            return false;
        }
        $output '';
        if (php_sapi_name() != "cli") {
            $lineBreak "<br />";
        } else {
            $lineBreak "\n";
        }
        if ($lineBreaksBefore 0) {
            for ($i 1$i <= $lineBreaksBefore$i++) {
                $output .= $lineBreak;
            }
        }
        $output .= $msg;
        if ($lineBreaksAfter 0) {
            for ($i 1$i <= $lineBreaksAfter$i++) {
                $output .= $lineBreak;
            }
        }
        echo $output;
        if (php_sapi_name() != "cli") {
            ob_flush();
        }
        flush();
    }
}/**
 * Instantiate Backup_Database and perform backup
 */
// Report all errorserror_reporting(E_ALL);// Set script max execution timeset_time_limit(900); // 15 minutesif (php_sapi_name() != "cli") {
    echo '<div style="font-family: monospace;">';
}$backupDatabase = new Backup_Database(DB_HOSTDB_USERDB_PASSWORDDB_NAME);$result $backupDatabase->backupTables(TABLESBACKUP_DIR) ? 'OK' 'NOT OK';$backupDatabase->obfPrint('Backup result: ' $result1);
if (php_sapi_name() != "cli") {
    echo '</div>';
}

?>

Comments


  1. sms gateway is for business of all sizes and budget.
    Bulk SMS stands for Short Message Service and refers to the
    sending of short text messages from one device to another in most cases
    from one mobile phone.


    ReplyDelete

Post a Comment

Popular posts from this blog

Send Email(with subject,body,attachment) using SSMTP through Terminal in linux?

1.Install ssmtp as              $ sudo apt-get update && sudo apt-get install ssmtp 2.Configure smtp file by editing the following file as, $ sudo gedit /etc/ssmtp/ssmtp.conf Update file with the following: AuthUser=Sendermail@gmail.com AuthPass=SenderPasswordforGMAIL FromLineOverride=YES mailhub=smtp.gmail.com:587 UseSTARTTLS=YES Now ssmtp.conf file should look like as the following one, AuthUser=Sendermail@gmail.com AuthPass=SenderPasswordforGMAIL # # Config file for sSMTP sendmail # # The person who gets all mail for userids < 1000 # Make this empty to disable rewriting. root=postmaster # The place where the mail goes. The actual machine name is required no # MX records are consulted. Commonly mailhosts are named mail.domain.com mailhub=smtp.gmail.com:587 # Where will the mail seem to come from? #rewriteDomain= # The full hostname hostname=tele-desktop118 # Are users allowed to set their own From: address? # Y

Upload and Retrieve an image from database

/*Create table in sql:*/ CREATE TABLE `images` ( `id` int(11) NOT NULL AUTO_INCREMENT, `image` longblob NOT NULL, `created` datetime NOT NULL, PRIMARY KEY (`id`) ); /*Uploading an image to Database*/ <?php if ( isset ( $_POST [ "submit" ])){ $check = getimagesize ( $_FILES [ "image" ][ "tmp_name" ]); if ( $check !== false ){ $image = $_FILES [ 'image' ][ 'tmp_name' ]; $imgContent = addslashes ( file_get_contents ( $image )); $dbHost = 'localhost' ; $dbUsername = 'root' ; $dbPassword = 'root' ; $dbName = 'sample' ; //Create connection and select DB $db = new mysqli( $dbHost , $dbUsername , $dbPassword , $dbName ); // Check connection if ( $db -> connect_error ){ die ( "Connection failed: " . $db -> connect_error ); } $dateTime = date ( "Y-m-d H:i:s" )