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:
Try this, You can change format zip to gz if you like :)
$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);
<?
// 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
?>
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);
}