0

what is the best way to backup a database using php and backing data from mysql,i have tried to look for tutorials online but i seem not to understand nicely well i wrote this though its not working nicely,im getting these errors and warnings

Warning: gzopen(backups/adminpanel/adminpanel_aggrement_1367616442.sql.gz): failed to open stream: No such file or directory in C:\xampp\htdocs\how are things\admin panel\backup.php on line 17

Notice: Undefined variable: time in C:\xampp\htdocs\how are things\admin panel\backup.php on line 30
The file--backups/adminpanel/aggrement_.sql.gz--could not be opened for writing.

the code on line 17 and 30 is this

if ($fp = gzopen ("$dir/{$db_name}_{$table}_{$bu_time}.sql.gz", 'w9')) {



  echo "<p>The file--$dir/{$table}_{$time}.sql.gz--could not be opened for writing.</p>\n";

this is my code

<?php 
$db_name = 'adminpanel';
$dir = "backups/$db_name";
if (!file_exists('path/to/directory')) {
    @mkdir('path/to/directory');
}
$bu_time = time();
$dbc = @mysqli_connect (localhost, root, nokiae71, adminpanel);
$q = 'SHOW TABLES';
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
    echo "<p>Backing up database '$db_name'.</p>\n";
    while (list($table) = mysqli_fetch_array($r, MYSQLI_NUM)) {
        $q2 = "SELECT * FROM $table";
        $r2 = mysqli_query($dbc, $q2);
        if (mysqli_num_rows($r2) > 0) {
            if ($fp = gzopen ("$dir/{$db_name}_{$table}_{$bu_time}.sql.gz", 'w9')) {
                                while ($row = mysqli_fetch_array($r2, MYSQLI_NUM)) {
                    foreach ($row as $value) { 

                        gzwrite ($fp, "'$value', ");
                    }
                    gzwrite ($fp, "\n"); 

                }               
                // Close the file:
                gzclose ($fp); 

            } else { // Could not create the file!
                echo "<p>The file--$dir/{$table}_{$time}.sql.gz--could not be opened for writing.</p>\n";
                break; 
            }   
        }
    } 
} else {
    echo "<p>The submitted database--$db_name--contains no tables.</p>\n";
}

?>

how can i make this work or is there any better script i can use out there...

4

1 回答 1

3

现在,这个解决方案使用cron,但我发现它很容易,所以我认为值得一提。您正在使用的服务器上可能已经安装了 Cron。

这是我安排 cron 每晚运行一次的命令:

mysqldump -h URL_TO_YOUR_DATABASE.com -u YOUR_MYSQL_USERNAME -pYOUR_MYSQL_PASSWORD --single-transaction YOUR_DATABASE_NAME | gzip > ~/PATH_WHERE_YOU_WANT_TO_PLACE_BACKUPS/db_backup_$(date +%Y-%m-%d).sql.gz

而已。

这告诉 mysqldump 将整个数据库转储为 sql。然后 gzip 压缩它。然后将其存储在您服务器上的某个位置,并将日期附加到文件名的末尾。

如果你真的想用 php 而不是 cron 来触发它,你可以尝试从 php 调用 mysqldump

于 2013-05-03T22:37:39.980 回答