使用CodeIgniter备份MySQL数据库


Backup MySQL database with CodeIgniter

我一直在研究CodeIgniter附带的用户指南。我对dbutil()方法非常感兴趣。特别是以下代码行:

// Load the DB utility class
$this->load->dbutil();
// Backup your entire database and assign it to a variable
$backup =& $this->dbutil->backup(); 
// Load the file helper and write the file to your server
$this->load->helper('file');
write_file('/path/to/mybackup.gz', $backup); 
// Load the download helper and send the file to your desktop
$this->load->helper('download');
force_download('mybackup.gz', $backup); 

它应该备份当前加载的MySQL数据库。但不幸的是,它不起作用,我收到以下消息:

遇到PHP错误

严重性:通知

消息:未定义的属性:CI_Loader::$dbutil

文件名:views/view.php

线路编号:10

致命错误:对中的非对象调用成员函数backup((C: 第10行上的''axamplep''htdocs''CodeIgniter''application''views''view.php

我在这里错过了什么?如有任何帮助,我们将不胜感激。

试试这个,如果你喜欢,你可以把zip格式改为gz:(

$this->load->dbutil();
$prefs = array(     
    'format'      => 'zip',             
    'filename'    => 'my_db_backup.sql'
    );

$backup =& $this->dbutil->backup($prefs); 
$db_name = 'backup-on-'. date("Y-m-d-H-i-s") .'.zip';
$save = 'pathtobkfolder/'.$db_name;
$this->load->helper('file');
write_file($save, $backup); 

$this->load->helper('download');
force_download($db_name, $backup);

使用php只适用于非常小的数据库。如果你增加了其他性能问题,你会很快遇到内存限制。

最有效的方法是使用mysqldump:创建一个转储

header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="dbbackup.sql.gz"');
passthru("mysqldump --user=xx --host=xx --password=xx dbname | gzip");

当然,您必须具有执行此操作所需的权限。

//load helpers
$this->load->helper('file');
$this->load->helper('download');
$this->load->library('zip');
//load database
$this->load->dbutil();
//create format
$db_format=array('format'=>'zip','filename'=>'backup.sql');
$backup=& $this->dbutil->backup($db_format);
// file name
$dbname='backup-on-'.date('d-m-y H:i').'.zip';
$save='assets/db_backup/'.$dbname;
// write file
write_file($save,$backup);
// and force download
force_download($dbname,$backup);
function backup($fileName='db_backup.zip'){
    // Load the DB utility class
    $this->load->dbutil();
    // Backup your entire database and assign it to a variable
    $backup =& $this->dbutil->backup();
    // Load the file helper and write the file to your server
    $this->load->helper('file');
    write_file(FCPATH.'/downloads/'.$fileName, $backup);
    // Load the download helper and send the file to your desktop
    $this->load->helper('download');
    force_download($fileName, $backup);
}

使用codeigniter 备份数据库的简单方法

public function db_backup()
{
    $this->load->helper('url');
    $this->load->helper('file');
    $this->load->helper('download');
    $this->load->library('zip');
    $this->load->dbutil();
    $db_format=array('format'=>'zip','filename'=>'my_db_backup.sql');
    $backup=& $this->dbutil->backup($db_format);
    $dbname='backup-on-'.date('Y-m-d').'.zip';
    $save='assets/db_backup/'.$dbname;
    write_file($save,$backup);
    force_download($dbname,$backup);
}`

如果您有幸在服务器上启用了exec()shell_exec()system()passthru()中的一个。也许你想使用以下内容:

public function db_backup()
{
    $DBUSER=$this->db->username;
    $DBPASSWD=$this->db->password;
    $DATABASE=$this->db->database;
    $filename = $DATABASE . "-" . date("Y-m-d_H-i-s") . ".sql.gz";
    $mime = "application/x-gzip";
    header( "Content-Type: " . $mime );
    header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
    // $cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";   
    $cmd = "mysqldump -u $DBUSER --password=$DBPASSWD --no-create-info --complete-insert $DATABASE | gzip --best";
    passthru( $cmd );
    exit(0);
}

试试这个。。。它已经过测试。。。如果你打算使用mysqli,那么它会很好。。。你可以把你的代码放在你的控制器或模型中,但我建议把这个放在你自己的模型中;从您的controller调用此函数。。。

public function db_backup()
{
       $this->load->dbutil();   
       $backup =& $this->dbutil->backup();  
       $this->load->helper('file');
       write_file('your_file_path/your_DB.zip', $backup); 
}

我对CodeIgniter非常陌生,但我成功地完成了备份。试试这个,它会成功工作,并且非常容易实现。在控制器中编写代码,并从视图页面调用用于备份的函数。做好准备,走吧,你就完了。

function dbbackup()
{
    $this->load->dbutil();   
    $backup =& $this->dbutil->backup();  
    $this->load->helper('file');
    write_file('<?php echo base_url();?>/downloads', $backup);
    $this->load->helper('download');
    force_download('mybackup.gz', $backup);
}

对于完整的应用程序备份,使用以下代码执行相同的过程:

function backup()
{
    $this->load->helper('download');
    $this->load->library('zip'); 
    $time = time(); 
    $this->zip->read_dir('D:xampp/htdocs/wms/');
    $this->zip->download('my_backup.'.$time.'.zip');
}

在这里,您可以使用您选择的任何路径。

 public function backup(){
    $this->load->dbutil();
    $config = array(     
        'format'      => 'zip',             
        'filename'    => 'insert-file-name.sql'
    );
    $backup =& $this->dbutil->backup($config); 
    $db_name = 'backup-on-'. date("Y-m-d-H-i-s") .'.zip';
    $save = 'uploads/'.$db_name;
    $this->load->helper('file');
    write_file($save, $backup); 
    $this->load->helper('download');
    force_download($db_name, $backup);
}

$content='SET SQL_MODE="NO_AUTO_ VALUE_ON_;;启动交易;SET time_ zone="+00:00";";

    if($tables = $this->db->list_tables()){
        foreach($tables as $table){
            $content .= ' DROP TABLE IF EXISTS `' . $table . '`;';
            $content .= $this->db->query('SHOW CREATE TABLE ' . $table)->row_array()['Create Table'] . ';'; 
            $fields = $this->db->list_fields($table);
            $table_data = $this->db->query('SELECT * FROM ' . $table)->result_array();
            $insert_field = '';
            $insert_values = '';
            if($fields && $table_data){
                $insert_field .= 'INSERT INTO `' . $table . '` (';
                foreach($fields as $field){
                    $insert_field .= '`' . $field . '`,';
                }
                $insert_field = substr($insert_field,0,-1);
                $insert_field .= ')';
                
                $insert_values .= ' VALUES ';
                foreach($table_data as $table_row){
                    $insert_values .= '(' ;
                    foreach($table_row as $column => $value){
                        $insert_values .= "'" . addslashes($value) . "',";
                    }
                    $insert_values = substr($insert_values,0,-1);
                    $insert_values .= '),';
                }
                $insert_values = substr($insert_values,0,-1) . '; ';
            }
            $content .= $insert_field . $insert_values;
        }
    }
    $file_path = "./uploads/backup-" . date('Y-m-d') . ".sql";
    $myfile = fopen($file_path, "w");
    fwrite($myfile, $content);
    fclose($myfile);

这些行是从代码点火器文档中获取的:

重要提示:为了初始化Utility类,您的数据库驱动程序必须已经在运行,因为实用程序类依赖于

调用此函数时,请检查数据库类是否已加载。或者,您可以在加载dbutil类$this->load->database(); 之前放置此行

试试这个!

$username = "root";
$password = "root";
$hostname = "localhost";
$dbname   = "raas";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($dbname . "_" .date("Y-m-d_H-i-s").".sql"));
$command = "C:'AppServ'MySQL'bin'mysqldump --add-drop-table --host=$hostname   --user=$username --password=$password ".$dbname;
system($command);

问题是在引导过程中很早就试图备份数据库。

当我试图破解CodeIgniter以使用备份我的数据库时,我遇到了同样的问题

$prefs = array(
            'ignore'=> array('codes_cdt','codes_cpt','codes_icd10_dx_order','codes_icd10_pcs_order','pharma'),
            'format'=>'gzip','filename','add_drop'=> TRUE,'add_insert'=>TRUE,'newline'=> "'n");
$filename = APPPATH.'''backups''' .'backup-' . date('d-m-Y') . ' .gz';
if(!file_exists($filename)){
    get_instance()->load->dbutil();
    file_put_contents( $filename, $this->dbutil->backup($prefs));
}

在我的config.php文件的底部。

把它移到一个模型上,允许它自动加载,你就可以了。

 <?
// Try this one, this works FOR both codeigniter and core PHP
            public function Export_Database()
                {
                    date_default_timezone_set('GMT');
                   // Load the file helper in codeigniter
                    $this->load->helper('file');

            $con = mysqli_connect("localhost","username","password","databasename");
            $tables = array();
            $query = mysqli_query($con, 'SHOW TABLES');
            while($row = mysqli_fetch_row($query)){
                 $tables[] = $row[0];
            }
            $result = 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";';
            $result .= 'SET time_zone = "+00:00";';
            foreach($tables as $table){
            $query = mysqli_query($con, 'SELECT * FROM `'.$table.'`');
            $num_fields = mysqli_num_fields($query);
            $result .= 'DROP TABLE IF EXISTS '.$table.';';
            $row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE `'.$table.'`'));
            $result .= "'n'n".$row2[1].";'n'n";
            for ($i = 0; $i < $num_fields; $i++) {
            while($row = mysqli_fetch_row($query)){
               $result .= '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])){
                       $result .= '"'.$row[$j].'"' ; 
                    }else{ 
                        $result .= '""';
                    }
                    if($j<($num_fields-1)){ 
                        $result .= ',';
                    }
                }
                $result .= ");'n";
            }
            }
            $result .="'n'n";
            }
            //Create Folder
            $folder = 'database/';
            if (!is_dir($folder))
            mkdir($folder, 0777, true);
            chmod($folder, 0777);
            $date = date('m-d-Y'); 
            $filename = $folder."db_filename_".$date; 
            $handle = fopen($filename.'.sql','w+');
            fwrite($handle,$result);
            fclose($handle);
            redirect('Dashboard');           

                } // end Export_Database function
            ?>

如果您想归档数据库,请使用函数$this->archive_database((;该函数将.sql文件保存在根文件夹中名为archives的文件夹中

// to intialize the path split the real path by dot .
        public function init_path($string){
            $array_path =  explode('.', $string);
            $realpath  = ''; 
            foreach ($array_path as $p)
            {
              
                $realpath .= $p;
                $realpath .= '/';
            }
            return $realpath;
            
        }
        
        // backup database function         
        public function archive_database($host = '',$user ='',$pass ='',$name ='', $path = '' , $download_allow = false ,       $tables=false, $backup_name=false){ 
            $CI = &get_instance();
            $CI->load->database();
            if($path != '')
            {
                $path = realpath($this->init_path($path));
                
            }else{
                if (!is_dir('archives/'))
            mkdir('archives/', 0777);
                $path = realpath($this->init_path('archives'));
            }
            if($host == '')
            {
                $host = $CI->db->hostname;
                
            }
            if($user == '')
            {
                $user = $CI->db->username;
                
            }
            if($pass == '')
            {
                $pass = $CI->db->password;
                
            }
            if($name == '')
            {
                $name = $CI->db->database;
                
            }
            
            set_time_limit(3000); 
            $mysqli = new mysqli($host,$user,$pass,$name); 
            $mysqli->select_db($name);
            $mysqli->query("SET NAMES 'utf8'");
            $queryTables = $mysqli->query('SHOW TABLES');
            while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } 
            if($tables !== false)
                { $target_tables = array_intersect( $target_tables, $tables); } 
            $content = "SET SQL_MODE = '"NO_AUTO_VALUE_ON_ZERO'";'r'nSET time_zone = '"+00:00'";'r'n'r'n'r'n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;'r'n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;'r'n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;'r'n/*!40101 SET NAMES utf8 */;'r'n--'r'n-- Database: `".$name."`'r'n--'r'n'r'n'r'n";
            foreach($target_tables as $table){
                if (empty($table)){ continue; } 
                $result = $mysqli->query('SELECT * FROM `'.$table.'`');
                $fields_amount=$result->field_count; 
                $rows_num=$mysqli->affected_rows; 
                $res = $mysqli->query('SHOW CREATE TABLE '.$table);
                $TableMLine=$res->fetch_row(); 
                $content .= "'n'n".$TableMLine[1].";'n'n";
                for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) {
                    while($row = $result->fetch_row())  { //when started (and every after 100 command cycle):
                        if ($st_counter%100 == 0 || $st_counter == 0 )  {$content .= "'nINSERT INTO ".$table." VALUES";}
                            $content .= "'n(";    for($j=0; $j<$fields_amount; $j++){ $row[$j] = str_replace("'n","''n", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '"'.$row[$j].'"' ;}  else{$content .= '""';}     if ($j<($fields_amount-1)){$content.= ',';}   }        $content .=")";
                        //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                        if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";} $st_counter=$st_counter+1;
                    }
                } $content .="'n'n'n";
            }
            $content .= "'r'n'r'n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;'r'n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;'r'n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
            $backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
            
            $fileLocation = $path .''''. $backup_name;
            $file = fopen($fileLocation,"w");
            fwrite($file,$content);
            fclose($file);
            
            
            if($download_allow){
            ob_get_clean(); header('Content-Type: application/octet-stream');   header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename='"".$backup_name."'"");
            }
            
            echo $content; exit;
        }

无需在路径添加base_url()