如何用PHP将mysql数据库(localhost)备份和恢复到云服务


how to backup and restore mysql database (localhost) to cloud service in PHP

如何在PHP中将mysql数据库(localhost)备份和恢复到Dropbox我尝试将此保存到我的硬盘驱动器,但如何保存到在线驱动器并从在线驱动器检索,以及如何使用PHP 显示所有保存的数据

首先使用以下代码在服务器上保存备份:

<?php
try {
    backup_tables('localhost','root','','database');
}
catch(Exception $e) {
  echo 'Error: ' .$e->getMessage();
}
    /* backup the db OR just a table */
    function backup_tables($host,$user,$pass,$name,$tables = '*')
    {
        $link = new mysqli($host, $user, $pass, $name);
        // Check connection
        if ($link->connect_error) {
            throw new Exception("Connection failed: " . $link->connect_error);
        }
        $return='';
        //get all of the tables
        if($tables == '*')
        {
            $tables = array();
            $result = mysqli_query($link,'SHOW TABLES');
            while($row = mysqli_fetch_row($result))
            {
                $tables[] = $row[0];
            }
        }
        else
        {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }
        //cycle through
        foreach($tables as $table)
        {
            $result = mysqli_query($link,'SELECT * FROM '.$table);
            $num_fields = mysqli_num_fields($result);
            $return.= 'DROP TABLE '.$table.';';
            $row2 = mysqli_fetch_row(mysqli_query($link,'SHOW CREATE TABLE '.$table));
            $return.= "'n'n".$row2[1].";'n'n";
            for ($i = 0; $i < $num_fields; $i++) 
            {
                while($row = mysqli_fetch_row($result))
                {
                    $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
        $time=time();
        $file_name='db-backup-'.$time.'-'.(md5(implode(',',$tables))).'.sql';
        $sql="INSERT INTO `backups` (`file_name`,`time`) VALUES ('$file_name','$time')";
        if(mysqli_query($link,$sql)){
            $handle = fopen($file_name,'w+');
            fwrite($handle,$return);
            fclose($handle);
        }
        else
        {
            throw new Exception("Unable to insert into backups database!");
        }
    }
?>

现在使用Dropbox API将其保存在Dropbox上。欲了解更多信息,请访问:Dropbox API

最后,使用php中的unlink()方法删除服务器上的文件。