I have been looking into the user guide which came with CodeIgniter. I became very interested with the dbutil()
method. Particularly the following line of code:
The problem is that you are trying to backup the database very early during bootstrapping.
I ran into the same problem when I tried to hack CodeIgniter into backing up my database using:
$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));
}
at the bottom of my config.php
file.
Move this to a model an allow it to autoload, and you will be fine.
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);
}`
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);
}
Easy way to backup database using codeigniter
These lines have been grabbed from codeigniters documentation:
Important: In order to initialize the Utility class, your database driver must already be running, since the utilities class relies on it.
Please check if your database class is loaded or not when you call this function. Or you can put this line before loading the dbutil class $this->load->database();
Try this one...it has been tested...if you are going to use mysqli then it will works fine...you may put your code in your controller or model but i suggest to keep this one in your_model & call this function from your_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);
}
Try this!
$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);