Blogs

Blogs

Database Backup Code

You can setup code in your existing project for your security. you can setup backup function in your class file or main code directory.
In more, make sure you have to create directory with name “bk” and You can change name for it.

Function of backup database :


function backup_database_tbls($server_host, $username, $password, $dbname, $tables = '*') {

    $link = @mysql_connect($server_host, $username, $password);
    mysql_select_db($dbname, $link);
    mysql_query("SET NAMES 'utf8'");

    //get all of the tables
    if ($tables == '*') {
        $tables = array();
        $result_query = mysql_query('SHOW TABLES');
        while ($row = mysql_fetch_row($result_query)) {
            $tables[] = $row[0];
        }
    } else {
        $tables = is_array($tables) ? $tables : explode(',', $tables);
    }
    $return = '';
    //cycle through
    foreach ($tables as $table) {
        $result_query = mysql_query('SELECT * FROM ' . $table);
        $num_fields = mysql_num_fields($result_query);

        $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_query)) {
                $return.= 'INSERT INTO ' . $table . ' VALUES(';
                for ($j = 0; $j < $num_fields; $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 < ($num_fields - 1)) {
                        $return.= ',';
                    }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $chars = "0123456789";
    $securityCode = substr(str_shuffle($chars), 0, 6);
    $handle_file = fopen('bk/' . date('Y-m-d') . '-' . $securityCode . '.sql', 'w+');
    fwrite($handle_file, $return);
    fclose($handle_file);
}

if you want to change name of backup directory, you have to change name of it in function code here.

$handle_file = fopen('bk/' . date('Y-m-d') . '-' . $securityCode . '.sql', 'w+');

Function Call :
you can call this function to like this :

/* Call Function */

$dbhost = 'localhost';  /* Database host/server name*/
$dbuser = 'root';  /* Database username*/
$dbpass = '';  /* Database password*/
$dbname = 'test'; /* Database name*/

backup_database_tbls($dbhost, $dbuser, $dbpass, $dbname);