通过zip文件导入数据库

时间:2017-04-25 05:34:30

标签: php

这是我的下载数据库zip文件的功能,它工作正常,但我想在数据库中插入它,并通过动态选择sql文件将其导入数据库

public function db_backup(){
    date_default_timezone_set('Asia/Calcutta');
    $this->load->dbutil(); 
    $prefs = array( 
        'format' => 'zip',  
        'add_drop' => TRUE,  
        'add_insert'=> TRUE, 
        'newline' => "\n"   
    ); 
    $backup =  $this->dbutil->backup($prefs); 
    $this->load->helper('file'); 
    $this->load->helper('download'); 
    $this->zip->archive(FCPATH.'backup/database/'.date('Y-m-d-His').'DbBackup.zip');
}

please provide me solution i tried vaious examples nothing works

public function restoredb($id = ''){


    $isi_file = file_get_contents('./backups/XXXXXXX.sql'); #here I want to give dynamic path
    $query = rtrim( $isi_file, "\n;" );
    $array_query = explode(";", $query);

    foreach($array_query as $query){
        $this->db->query($query);
    }

}

以上功能恢复数据库但不能正常工作

2 个答案:

答案 0 :(得分:0)

导出和导入数据时尝试此操作

导出

$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD -h$HOST $DATABASE > backup.sql";   
        shell_exec( $cmd );

导入/恢复

$cmd = "mysql -u $DBUSER --password=$DBPASSWD -h$HOST -D$database < backup.sql";   
        shell_exec( $cmd );

答案 1 :(得分:0)

$backup = read_file('path/to/file.sql');
$sql_clean = '';
    foreach (explode("\n", $backup) as $line){
        if(isset($line[0]) && $line[0] != "#"){
            $sql_clean .= $line."\n";
        }
    }
    foreach (explode(";\n", $sql_clean) as $sql){
        $sql = trim($sql);
        if($sql){
            $this->db->query($sql);
        } 
    }

试试这个我希望它有所帮助