Friday, May 11, 2018

Database Backup using php Mysql


//Backup Manually
$dbHost = 'localhost';
$dbName = 'billing';
$dbUsername = 'root';
$dbPassword = '';
$tables = '*';
$return = '';
$folder = "db_backup/";

//connect & select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

//get all of the tables
if ($tables == '*') {
    $tables = array();
    $result = $db->query("SHOW TABLES");
    while ($row = $result->fetch_row()) {
        $tables[] = $row[0];
    }
} else {
    $tables = is_array($tables) ? $tables : explode(',', $tables);
}

//loop through the tables
foreach ($tables as $table) {
    $result = $db->query("SELECT * FROM $table");
    $numColumns = $result->field_count;

    $return .= "DROP TABLE IF EXISTS $table;";

    $result2 = $db->query("SHOW CREATE TABLE $table");
    $row2 = $result2->fetch_row();

    $return .= "\n\n" . $row2[1] . ";\n\n";

    for ($i = 0; $i < $numColumns; $i++) {
        while ($row = $result->fetch_row()) {
            $return .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $numColumns; $j++) {
                $row[$j] = addslashes($row[$j]);
                $row[$j] = preg_replace("/\n/", "/\\n/", $row[$j]);
                if (isset($row[$j])) {
                    $return .= '"' . $row[$j] . '"';
                } else {
                    $return .= '""';
                }
                if ($j < ($numColumns - 1)) {
                    $return .= ',';
                }
            }
            $return .= ");\n";
        }
    }

    $return .= "\n\n\n";
}

// Create Backup Folder
if (!is_dir($folder))
    mkdir($folder, 0775, true);
//chmod($folder, 0775);

$date = date('m-d-Y-H-i-s', time());
$filename = $dbName . "_" . $date . ".sql";
$path = $folder . $filename;

//save file
$handle = fopen($path, 'w+');
fwrite($handle, $return);
fclose($handle);

if (file_exists($path)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($path) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($path));
    readfile($path);
//            echo $return;
    exit;
}

NOTE: when you import this database into your phpmyadmin at that time uncheck the Enable foreign key checks 

No comments:

Post a Comment

Product Category Demo in laravel

https://drive.google.com/file/d/1kuyeT3LA22IuN3o_kypOyXesEXMLv31e/view?usp=sharing