Backup MySQL database with CodeIgniter












8















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:



// 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);


It is supposed to backup the currently loaded MySQL database. But unfortunately, it is not working and I get the following message:




A PHP Error was encountered



Severity: Notice



Message: Undefined property: CI_Loader::$dbutil



Filename: views/view.php



Line Number: 10



Fatal error: Call to a member function backup() on a non-object in
C:xampphtdocsCodeIgniterapplicationviewsview.php on line 10




What am I missing here? Any help would be really appreciated.










share|improve this question

























  • Is the main DB class loaded (autoloaded or loaded through $this->load->database();)? Also, how come you are getting this error on a view, shouldn't this backup code be on a controller?

    – dakdad
    Dec 30 '12 at 19:26











  • @muttalebm you need to remove last two lines from your above code.

    – Raham
    Dec 20 '14 at 5:11











  • Code should be executed inside a controller, not a view.

    – Nabil SADKI
    May 3 '17 at 13:41
















8















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:



// 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);


It is supposed to backup the currently loaded MySQL database. But unfortunately, it is not working and I get the following message:




A PHP Error was encountered



Severity: Notice



Message: Undefined property: CI_Loader::$dbutil



Filename: views/view.php



Line Number: 10



Fatal error: Call to a member function backup() on a non-object in
C:xampphtdocsCodeIgniterapplicationviewsview.php on line 10




What am I missing here? Any help would be really appreciated.










share|improve this question

























  • Is the main DB class loaded (autoloaded or loaded through $this->load->database();)? Also, how come you are getting this error on a view, shouldn't this backup code be on a controller?

    – dakdad
    Dec 30 '12 at 19:26











  • @muttalebm you need to remove last two lines from your above code.

    – Raham
    Dec 20 '14 at 5:11











  • Code should be executed inside a controller, not a view.

    – Nabil SADKI
    May 3 '17 at 13:41














8












8








8


3






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:



// 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);


It is supposed to backup the currently loaded MySQL database. But unfortunately, it is not working and I get the following message:




A PHP Error was encountered



Severity: Notice



Message: Undefined property: CI_Loader::$dbutil



Filename: views/view.php



Line Number: 10



Fatal error: Call to a member function backup() on a non-object in
C:xampphtdocsCodeIgniterapplicationviewsview.php on line 10




What am I missing here? Any help would be really appreciated.










share|improve this question
















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:



// 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);


It is supposed to backup the currently loaded MySQL database. But unfortunately, it is not working and I get the following message:




A PHP Error was encountered



Severity: Notice



Message: Undefined property: CI_Loader::$dbutil



Filename: views/view.php



Line Number: 10



Fatal error: Call to a member function backup() on a non-object in
C:xampphtdocsCodeIgniterapplicationviewsview.php on line 10




What am I missing here? Any help would be really appreciated.







php mysql database codeigniter






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 30 '12 at 19:14









halfer

14.7k759116




14.7k759116










asked Dec 30 '12 at 17:46









muttalebmmuttalebm

3551420




3551420













  • Is the main DB class loaded (autoloaded or loaded through $this->load->database();)? Also, how come you are getting this error on a view, shouldn't this backup code be on a controller?

    – dakdad
    Dec 30 '12 at 19:26











  • @muttalebm you need to remove last two lines from your above code.

    – Raham
    Dec 20 '14 at 5:11











  • Code should be executed inside a controller, not a view.

    – Nabil SADKI
    May 3 '17 at 13:41



















  • Is the main DB class loaded (autoloaded or loaded through $this->load->database();)? Also, how come you are getting this error on a view, shouldn't this backup code be on a controller?

    – dakdad
    Dec 30 '12 at 19:26











  • @muttalebm you need to remove last two lines from your above code.

    – Raham
    Dec 20 '14 at 5:11











  • Code should be executed inside a controller, not a view.

    – Nabil SADKI
    May 3 '17 at 13:41

















Is the main DB class loaded (autoloaded or loaded through $this->load->database();)? Also, how come you are getting this error on a view, shouldn't this backup code be on a controller?

– dakdad
Dec 30 '12 at 19:26





Is the main DB class loaded (autoloaded or loaded through $this->load->database();)? Also, how come you are getting this error on a view, shouldn't this backup code be on a controller?

– dakdad
Dec 30 '12 at 19:26













@muttalebm you need to remove last two lines from your above code.

– Raham
Dec 20 '14 at 5:11





@muttalebm you need to remove last two lines from your above code.

– Raham
Dec 20 '14 at 5:11













Code should be executed inside a controller, not a view.

– Nabil SADKI
May 3 '17 at 13:41





Code should be executed inside a controller, not a view.

– Nabil SADKI
May 3 '17 at 13:41












14 Answers
14






active

oldest

votes


















21














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);





share|improve this answer





















  • 1





    Thanks a lot Saleem. I was looking for the zip format. But my original problem was fixed. I was trying to call the dbutil() method from the view which should have been done from the controller. A very idiotic moment for me :( Anyways thanks for your help buddy :D

    – muttalebm
    Dec 31 '12 at 6:34











  • No problem, Good to hear that you have managed to solve the issue. Take care

    – Saleem
    Dec 31 '12 at 10:37











  • This solution works for me

    – dian
    Sep 23 '16 at 8:23











  • works for me, cheers!

    – Matt Sephton
    Dec 12 '16 at 14:23











  • Thanks a lot, well now i have another issue how can i update database from one to another one,

    – Freddy Sidauruk
    Feb 17 '17 at 3:29



















7














doing that using php will only work for very small databases. You will very fast run into memory limits - if you increase that other performance problems.



What works best is to create a dump using 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");


of course you must have the required permissions to do that.






share|improve this answer
























  • Thanks but I am working with a small database over a office network

    – muttalebm
    Dec 30 '12 at 18:59











  • Why use passthru over exec here?

    – Chords
    Aug 30 '13 at 15:37



















2














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






share|improve this answer

































    1














    If you are lucky enough to have one of the exec(), shell_exec(), system() or passthru() enabled on your server. Maybe you would want to use the following:



    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);
    }





    share|improve this answer































      1














      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);
      }





      share|improve this answer
























      • pasa mara da khu kar ne kai

        – Nasir
        Sep 6 '16 at 11:52











      • @Nasir its working dear.

        – Raham
        Sep 7 '16 at 5:13



















      1














      I am extremely new to CodeIgniter but I succeeded to do this backup. Try this, it will work successfully and is very easy to implement. Write the code in your controller and call the function from your view page which use for backup. Get set, go and you are done.



      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);
      }


      For your full application backup, do the same procedure with the following code:



      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');
      }


      Here you can use any path of your choice.






      share|improve this answer


























      • awesome. working great

        – Amir Iqbal
        Oct 3 '16 at 16:19



















      1














      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);

      }`





      share|improve this answer
























      • use these it work great for me

        – Rahul patel
        Nov 16 '18 at 10:12



















      0














      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();






      share|improve this answer































        0














        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:AppServMySQLbinmysqldump --add-drop-table --host=$hostname --user=$username --password=$password ".$dbname;

        system($command);





        share|improve this answer

































          0














          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.






          share|improve this answer

































            0














             <?

            // 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 .= "nn".$row2[1].";nn";

            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 .="nn";
            }

            //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
            ?>





            share|improve this answer

































              0














              // 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";rnSET time_zone = "+00:00";rnrnrn/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;rn/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;rn/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;rn/*!40101 SET NAMES utf8 */;rn--rn-- Database: `".$name."`rn--rnrnrn";
              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 .= "nn".$TableMLine[1].";nn";
              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 .="nnn";
              }
              $content .= "rnrn/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;rn/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;rn/*!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;
              }





              share|improve this answer
























              • Ahmad please explain your code. Little explanation with code always helps better.

                – Olcay Ertaş
                Mar 18 '17 at 14:08











              • if you want to archive your database use the function $this->archive_database(); this function save the .sql file in the folder named archives in the root folder

                – ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ
                Mar 18 '17 at 14:43











              • Not in the comment :)

                – Olcay Ertaş
                Mar 19 '17 at 10:16



















              0














               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);

              }





              share|improve this answer































                -3














                No need to add base_url() at path






                share|improve this answer


























                • @CybernatiC the question is not say about base_url();.Your answer is not related to the question asked.

                  – Raham
                  Nov 10 '15 at 11:07












                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14093020%2fbackup-mysql-database-with-codeigniter%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                14 Answers
                14






                active

                oldest

                votes








                14 Answers
                14






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                21














                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);





                share|improve this answer





















                • 1





                  Thanks a lot Saleem. I was looking for the zip format. But my original problem was fixed. I was trying to call the dbutil() method from the view which should have been done from the controller. A very idiotic moment for me :( Anyways thanks for your help buddy :D

                  – muttalebm
                  Dec 31 '12 at 6:34











                • No problem, Good to hear that you have managed to solve the issue. Take care

                  – Saleem
                  Dec 31 '12 at 10:37











                • This solution works for me

                  – dian
                  Sep 23 '16 at 8:23











                • works for me, cheers!

                  – Matt Sephton
                  Dec 12 '16 at 14:23











                • Thanks a lot, well now i have another issue how can i update database from one to another one,

                  – Freddy Sidauruk
                  Feb 17 '17 at 3:29
















                21














                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);





                share|improve this answer





















                • 1





                  Thanks a lot Saleem. I was looking for the zip format. But my original problem was fixed. I was trying to call the dbutil() method from the view which should have been done from the controller. A very idiotic moment for me :( Anyways thanks for your help buddy :D

                  – muttalebm
                  Dec 31 '12 at 6:34











                • No problem, Good to hear that you have managed to solve the issue. Take care

                  – Saleem
                  Dec 31 '12 at 10:37











                • This solution works for me

                  – dian
                  Sep 23 '16 at 8:23











                • works for me, cheers!

                  – Matt Sephton
                  Dec 12 '16 at 14:23











                • Thanks a lot, well now i have another issue how can i update database from one to another one,

                  – Freddy Sidauruk
                  Feb 17 '17 at 3:29














                21












                21








                21







                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);





                share|improve this answer















                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);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 24 '18 at 8:47

























                answered Dec 31 '12 at 2:13









                SaleemSaleem

                528723




                528723








                • 1





                  Thanks a lot Saleem. I was looking for the zip format. But my original problem was fixed. I was trying to call the dbutil() method from the view which should have been done from the controller. A very idiotic moment for me :( Anyways thanks for your help buddy :D

                  – muttalebm
                  Dec 31 '12 at 6:34











                • No problem, Good to hear that you have managed to solve the issue. Take care

                  – Saleem
                  Dec 31 '12 at 10:37











                • This solution works for me

                  – dian
                  Sep 23 '16 at 8:23











                • works for me, cheers!

                  – Matt Sephton
                  Dec 12 '16 at 14:23











                • Thanks a lot, well now i have another issue how can i update database from one to another one,

                  – Freddy Sidauruk
                  Feb 17 '17 at 3:29














                • 1





                  Thanks a lot Saleem. I was looking for the zip format. But my original problem was fixed. I was trying to call the dbutil() method from the view which should have been done from the controller. A very idiotic moment for me :( Anyways thanks for your help buddy :D

                  – muttalebm
                  Dec 31 '12 at 6:34











                • No problem, Good to hear that you have managed to solve the issue. Take care

                  – Saleem
                  Dec 31 '12 at 10:37











                • This solution works for me

                  – dian
                  Sep 23 '16 at 8:23











                • works for me, cheers!

                  – Matt Sephton
                  Dec 12 '16 at 14:23











                • Thanks a lot, well now i have another issue how can i update database from one to another one,

                  – Freddy Sidauruk
                  Feb 17 '17 at 3:29








                1




                1





                Thanks a lot Saleem. I was looking for the zip format. But my original problem was fixed. I was trying to call the dbutil() method from the view which should have been done from the controller. A very idiotic moment for me :( Anyways thanks for your help buddy :D

                – muttalebm
                Dec 31 '12 at 6:34





                Thanks a lot Saleem. I was looking for the zip format. But my original problem was fixed. I was trying to call the dbutil() method from the view which should have been done from the controller. A very idiotic moment for me :( Anyways thanks for your help buddy :D

                – muttalebm
                Dec 31 '12 at 6:34













                No problem, Good to hear that you have managed to solve the issue. Take care

                – Saleem
                Dec 31 '12 at 10:37





                No problem, Good to hear that you have managed to solve the issue. Take care

                – Saleem
                Dec 31 '12 at 10:37













                This solution works for me

                – dian
                Sep 23 '16 at 8:23





                This solution works for me

                – dian
                Sep 23 '16 at 8:23













                works for me, cheers!

                – Matt Sephton
                Dec 12 '16 at 14:23





                works for me, cheers!

                – Matt Sephton
                Dec 12 '16 at 14:23













                Thanks a lot, well now i have another issue how can i update database from one to another one,

                – Freddy Sidauruk
                Feb 17 '17 at 3:29





                Thanks a lot, well now i have another issue how can i update database from one to another one,

                – Freddy Sidauruk
                Feb 17 '17 at 3:29













                7














                doing that using php will only work for very small databases. You will very fast run into memory limits - if you increase that other performance problems.



                What works best is to create a dump using 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");


                of course you must have the required permissions to do that.






                share|improve this answer
























                • Thanks but I am working with a small database over a office network

                  – muttalebm
                  Dec 30 '12 at 18:59











                • Why use passthru over exec here?

                  – Chords
                  Aug 30 '13 at 15:37
















                7














                doing that using php will only work for very small databases. You will very fast run into memory limits - if you increase that other performance problems.



                What works best is to create a dump using 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");


                of course you must have the required permissions to do that.






                share|improve this answer
























                • Thanks but I am working with a small database over a office network

                  – muttalebm
                  Dec 30 '12 at 18:59











                • Why use passthru over exec here?

                  – Chords
                  Aug 30 '13 at 15:37














                7












                7








                7







                doing that using php will only work for very small databases. You will very fast run into memory limits - if you increase that other performance problems.



                What works best is to create a dump using 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");


                of course you must have the required permissions to do that.






                share|improve this answer













                doing that using php will only work for very small databases. You will very fast run into memory limits - if you increase that other performance problems.



                What works best is to create a dump using 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");


                of course you must have the required permissions to do that.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 30 '12 at 18:18









                Niko SamsNiko Sams

                3,14421940




                3,14421940













                • Thanks but I am working with a small database over a office network

                  – muttalebm
                  Dec 30 '12 at 18:59











                • Why use passthru over exec here?

                  – Chords
                  Aug 30 '13 at 15:37



















                • Thanks but I am working with a small database over a office network

                  – muttalebm
                  Dec 30 '12 at 18:59











                • Why use passthru over exec here?

                  – Chords
                  Aug 30 '13 at 15:37

















                Thanks but I am working with a small database over a office network

                – muttalebm
                Dec 30 '12 at 18:59





                Thanks but I am working with a small database over a office network

                – muttalebm
                Dec 30 '12 at 18:59













                Why use passthru over exec here?

                – Chords
                Aug 30 '13 at 15:37





                Why use passthru over exec here?

                – Chords
                Aug 30 '13 at 15:37











                2














                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






                share|improve this answer






























                  2














                  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






                  share|improve this answer




























                    2












                    2








                    2







                    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






                    share|improve this answer















                    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







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 29 '16 at 11:35

























                    answered Feb 29 '16 at 11:29









                    user3260138user3260138

                    213




                    213























                        1














                        If you are lucky enough to have one of the exec(), shell_exec(), system() or passthru() enabled on your server. Maybe you would want to use the following:



                        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);
                        }





                        share|improve this answer




























                          1














                          If you are lucky enough to have one of the exec(), shell_exec(), system() or passthru() enabled on your server. Maybe you would want to use the following:



                          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);
                          }





                          share|improve this answer


























                            1












                            1








                            1







                            If you are lucky enough to have one of the exec(), shell_exec(), system() or passthru() enabled on your server. Maybe you would want to use the following:



                            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);
                            }





                            share|improve this answer













                            If you are lucky enough to have one of the exec(), shell_exec(), system() or passthru() enabled on your server. Maybe you would want to use the following:



                            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);
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Apr 24 '14 at 10:04









                            Kamran AhmedKamran Ahmed

                            4,687154981




                            4,687154981























                                1














                                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);
                                }





                                share|improve this answer
























                                • pasa mara da khu kar ne kai

                                  – Nasir
                                  Sep 6 '16 at 11:52











                                • @Nasir its working dear.

                                  – Raham
                                  Sep 7 '16 at 5:13
















                                1














                                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);
                                }





                                share|improve this answer
























                                • pasa mara da khu kar ne kai

                                  – Nasir
                                  Sep 6 '16 at 11:52











                                • @Nasir its working dear.

                                  – Raham
                                  Sep 7 '16 at 5:13














                                1












                                1








                                1







                                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);
                                }





                                share|improve this answer













                                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);
                                }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Dec 16 '14 at 10:10









                                RahamRaham

                                2,30411725




                                2,30411725













                                • pasa mara da khu kar ne kai

                                  – Nasir
                                  Sep 6 '16 at 11:52











                                • @Nasir its working dear.

                                  – Raham
                                  Sep 7 '16 at 5:13



















                                • pasa mara da khu kar ne kai

                                  – Nasir
                                  Sep 6 '16 at 11:52











                                • @Nasir its working dear.

                                  – Raham
                                  Sep 7 '16 at 5:13

















                                pasa mara da khu kar ne kai

                                – Nasir
                                Sep 6 '16 at 11:52





                                pasa mara da khu kar ne kai

                                – Nasir
                                Sep 6 '16 at 11:52













                                @Nasir its working dear.

                                – Raham
                                Sep 7 '16 at 5:13





                                @Nasir its working dear.

                                – Raham
                                Sep 7 '16 at 5:13











                                1














                                I am extremely new to CodeIgniter but I succeeded to do this backup. Try this, it will work successfully and is very easy to implement. Write the code in your controller and call the function from your view page which use for backup. Get set, go and you are done.



                                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);
                                }


                                For your full application backup, do the same procedure with the following code:



                                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');
                                }


                                Here you can use any path of your choice.






                                share|improve this answer


























                                • awesome. working great

                                  – Amir Iqbal
                                  Oct 3 '16 at 16:19
















                                1














                                I am extremely new to CodeIgniter but I succeeded to do this backup. Try this, it will work successfully and is very easy to implement. Write the code in your controller and call the function from your view page which use for backup. Get set, go and you are done.



                                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);
                                }


                                For your full application backup, do the same procedure with the following code:



                                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');
                                }


                                Here you can use any path of your choice.






                                share|improve this answer


























                                • awesome. working great

                                  – Amir Iqbal
                                  Oct 3 '16 at 16:19














                                1












                                1








                                1







                                I am extremely new to CodeIgniter but I succeeded to do this backup. Try this, it will work successfully and is very easy to implement. Write the code in your controller and call the function from your view page which use for backup. Get set, go and you are done.



                                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);
                                }


                                For your full application backup, do the same procedure with the following code:



                                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');
                                }


                                Here you can use any path of your choice.






                                share|improve this answer















                                I am extremely new to CodeIgniter but I succeeded to do this backup. Try this, it will work successfully and is very easy to implement. Write the code in your controller and call the function from your view page which use for backup. Get set, go and you are done.



                                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);
                                }


                                For your full application backup, do the same procedure with the following code:



                                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');
                                }


                                Here you can use any path of your choice.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Oct 13 '15 at 22:34









                                Nisse Engström

                                4,18392236




                                4,18392236










                                answered Dec 19 '14 at 11:08









                                sangitasangita

                                112




                                112













                                • awesome. working great

                                  – Amir Iqbal
                                  Oct 3 '16 at 16:19



















                                • awesome. working great

                                  – Amir Iqbal
                                  Oct 3 '16 at 16:19

















                                awesome. working great

                                – Amir Iqbal
                                Oct 3 '16 at 16:19





                                awesome. working great

                                – Amir Iqbal
                                Oct 3 '16 at 16:19











                                1














                                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);

                                }`





                                share|improve this answer
























                                • use these it work great for me

                                  – Rahul patel
                                  Nov 16 '18 at 10:12
















                                1














                                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);

                                }`





                                share|improve this answer
























                                • use these it work great for me

                                  – Rahul patel
                                  Nov 16 '18 at 10:12














                                1












                                1








                                1







                                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);

                                }`





                                share|improve this answer













                                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);

                                }`






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Nov 16 '18 at 10:12









                                Rahul patelRahul patel

                                111




                                111













                                • use these it work great for me

                                  – Rahul patel
                                  Nov 16 '18 at 10:12



















                                • use these it work great for me

                                  – Rahul patel
                                  Nov 16 '18 at 10:12

















                                use these it work great for me

                                – Rahul patel
                                Nov 16 '18 at 10:12





                                use these it work great for me

                                – Rahul patel
                                Nov 16 '18 at 10:12











                                0














                                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();






                                share|improve this answer




























                                  0














                                  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();






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    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();






                                    share|improve this answer













                                    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();







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Dec 31 '12 at 8:33









                                    Code PrankCode Prank

                                    3,51642343




                                    3,51642343























                                        0














                                        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:AppServMySQLbinmysqldump --add-drop-table --host=$hostname --user=$username --password=$password ".$dbname;

                                        system($command);





                                        share|improve this answer






























                                          0














                                          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:AppServMySQLbinmysqldump --add-drop-table --host=$hostname --user=$username --password=$password ".$dbname;

                                          system($command);





                                          share|improve this answer




























                                            0












                                            0








                                            0







                                            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:AppServMySQLbinmysqldump --add-drop-table --host=$hostname --user=$username --password=$password ".$dbname;

                                            system($command);





                                            share|improve this answer















                                            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:AppServMySQLbinmysqldump --add-drop-table --host=$hostname --user=$username --password=$password ".$dbname;

                                            system($command);






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Jun 16 '14 at 12:44









                                            OGHaza

                                            4,53861828




                                            4,53861828










                                            answered Jun 16 '14 at 12:25









                                            Flaviano SilvaFlaviano Silva

                                            1175




                                            1175























                                                0














                                                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.






                                                share|improve this answer






























                                                  0














                                                  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.






                                                  share|improve this answer




























                                                    0












                                                    0








                                                    0







                                                    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.






                                                    share|improve this answer















                                                    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.







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Oct 13 '15 at 22:42









                                                    Nisse Engström

                                                    4,18392236




                                                    4,18392236










                                                    answered Dec 8 '14 at 5:36









                                                    ZalabozaZalaboza

                                                    4,0671448107




                                                    4,0671448107























                                                        0














                                                         <?

                                                        // 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 .= "nn".$row2[1].";nn";

                                                        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 .="nn";
                                                        }

                                                        //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
                                                        ?>





                                                        share|improve this answer






























                                                          0














                                                           <?

                                                          // 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 .= "nn".$row2[1].";nn";

                                                          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 .="nn";
                                                          }

                                                          //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
                                                          ?>





                                                          share|improve this answer




























                                                            0












                                                            0








                                                            0







                                                             <?

                                                            // 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 .= "nn".$row2[1].";nn";

                                                            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 .="nn";
                                                            }

                                                            //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
                                                            ?>





                                                            share|improve this answer















                                                             <?

                                                            // 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 .= "nn".$row2[1].";nn";

                                                            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 .="nn";
                                                            }

                                                            //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
                                                            ?>






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Jan 31 '17 at 5:40

























                                                            answered Jan 31 '17 at 5:15









                                                            Imran Malik AryanImran Malik Aryan

                                                            14




                                                            14























                                                                0














                                                                // 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";rnSET time_zone = "+00:00";rnrnrn/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;rn/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;rn/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;rn/*!40101 SET NAMES utf8 */;rn--rn-- Database: `".$name."`rn--rnrnrn";
                                                                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 .= "nn".$TableMLine[1].";nn";
                                                                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 .="nnn";
                                                                }
                                                                $content .= "rnrn/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;rn/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;rn/*!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;
                                                                }





                                                                share|improve this answer
























                                                                • Ahmad please explain your code. Little explanation with code always helps better.

                                                                  – Olcay Ertaş
                                                                  Mar 18 '17 at 14:08











                                                                • if you want to archive your database use the function $this->archive_database(); this function save the .sql file in the folder named archives in the root folder

                                                                  – ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ
                                                                  Mar 18 '17 at 14:43











                                                                • Not in the comment :)

                                                                  – Olcay Ertaş
                                                                  Mar 19 '17 at 10:16
















                                                                0














                                                                // 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";rnSET time_zone = "+00:00";rnrnrn/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;rn/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;rn/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;rn/*!40101 SET NAMES utf8 */;rn--rn-- Database: `".$name."`rn--rnrnrn";
                                                                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 .= "nn".$TableMLine[1].";nn";
                                                                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 .="nnn";
                                                                }
                                                                $content .= "rnrn/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;rn/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;rn/*!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;
                                                                }





                                                                share|improve this answer
























                                                                • Ahmad please explain your code. Little explanation with code always helps better.

                                                                  – Olcay Ertaş
                                                                  Mar 18 '17 at 14:08











                                                                • if you want to archive your database use the function $this->archive_database(); this function save the .sql file in the folder named archives in the root folder

                                                                  – ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ
                                                                  Mar 18 '17 at 14:43











                                                                • Not in the comment :)

                                                                  – Olcay Ertaş
                                                                  Mar 19 '17 at 10:16














                                                                0












                                                                0








                                                                0







                                                                // 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";rnSET time_zone = "+00:00";rnrnrn/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;rn/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;rn/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;rn/*!40101 SET NAMES utf8 */;rn--rn-- Database: `".$name."`rn--rnrnrn";
                                                                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 .= "nn".$TableMLine[1].";nn";
                                                                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 .="nnn";
                                                                }
                                                                $content .= "rnrn/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;rn/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;rn/*!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;
                                                                }





                                                                share|improve this answer













                                                                // 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";rnSET time_zone = "+00:00";rnrnrn/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;rn/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;rn/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;rn/*!40101 SET NAMES utf8 */;rn--rn-- Database: `".$name."`rn--rnrnrn";
                                                                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 .= "nn".$TableMLine[1].";nn";
                                                                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 .="nnn";
                                                                }
                                                                $content .= "rnrn/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;rn/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;rn/*!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;
                                                                }






                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Mar 18 '17 at 13:44









                                                                ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ

                                                                413




                                                                413













                                                                • Ahmad please explain your code. Little explanation with code always helps better.

                                                                  – Olcay Ertaş
                                                                  Mar 18 '17 at 14:08











                                                                • if you want to archive your database use the function $this->archive_database(); this function save the .sql file in the folder named archives in the root folder

                                                                  – ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ
                                                                  Mar 18 '17 at 14:43











                                                                • Not in the comment :)

                                                                  – Olcay Ertaş
                                                                  Mar 19 '17 at 10:16



















                                                                • Ahmad please explain your code. Little explanation with code always helps better.

                                                                  – Olcay Ertaş
                                                                  Mar 18 '17 at 14:08











                                                                • if you want to archive your database use the function $this->archive_database(); this function save the .sql file in the folder named archives in the root folder

                                                                  – ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ
                                                                  Mar 18 '17 at 14:43











                                                                • Not in the comment :)

                                                                  – Olcay Ertaş
                                                                  Mar 19 '17 at 10:16

















                                                                Ahmad please explain your code. Little explanation with code always helps better.

                                                                – Olcay Ertaş
                                                                Mar 18 '17 at 14:08





                                                                Ahmad please explain your code. Little explanation with code always helps better.

                                                                – Olcay Ertaş
                                                                Mar 18 '17 at 14:08













                                                                if you want to archive your database use the function $this->archive_database(); this function save the .sql file in the folder named archives in the root folder

                                                                – ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ
                                                                Mar 18 '17 at 14:43





                                                                if you want to archive your database use the function $this->archive_database(); this function save the .sql file in the folder named archives in the root folder

                                                                – ᗗᖺᗰᗅᖱ ᔜᕱᒺᕨᗁ
                                                                Mar 18 '17 at 14:43













                                                                Not in the comment :)

                                                                – Olcay Ertaş
                                                                Mar 19 '17 at 10:16





                                                                Not in the comment :)

                                                                – Olcay Ertaş
                                                                Mar 19 '17 at 10:16











                                                                0














                                                                 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);

                                                                }





                                                                share|improve this answer




























                                                                  0














                                                                   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);

                                                                  }





                                                                  share|improve this answer


























                                                                    0












                                                                    0








                                                                    0







                                                                     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);

                                                                    }





                                                                    share|improve this answer













                                                                     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);

                                                                    }






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Feb 19 at 10:01









                                                                    Sandeep YadavSandeep Yadav

                                                                    93




                                                                    93























                                                                        -3














                                                                        No need to add base_url() at path






                                                                        share|improve this answer


























                                                                        • @CybernatiC the question is not say about base_url();.Your answer is not related to the question asked.

                                                                          – Raham
                                                                          Nov 10 '15 at 11:07
















                                                                        -3














                                                                        No need to add base_url() at path






                                                                        share|improve this answer


























                                                                        • @CybernatiC the question is not say about base_url();.Your answer is not related to the question asked.

                                                                          – Raham
                                                                          Nov 10 '15 at 11:07














                                                                        -3












                                                                        -3








                                                                        -3







                                                                        No need to add base_url() at path






                                                                        share|improve this answer















                                                                        No need to add base_url() at path







                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited Oct 11 '15 at 16:48









                                                                        Sruit A.Suk

                                                                        4,95364356




                                                                        4,95364356










                                                                        answered Oct 11 '15 at 8:49









                                                                        CybernatiCCybernatiC

                                                                        111




                                                                        111













                                                                        • @CybernatiC the question is not say about base_url();.Your answer is not related to the question asked.

                                                                          – Raham
                                                                          Nov 10 '15 at 11:07



















                                                                        • @CybernatiC the question is not say about base_url();.Your answer is not related to the question asked.

                                                                          – Raham
                                                                          Nov 10 '15 at 11:07

















                                                                        @CybernatiC the question is not say about base_url();.Your answer is not related to the question asked.

                                                                        – Raham
                                                                        Nov 10 '15 at 11:07





                                                                        @CybernatiC the question is not say about base_url();.Your answer is not related to the question asked.

                                                                        – Raham
                                                                        Nov 10 '15 at 11:07


















                                                                        draft saved

                                                                        draft discarded




















































                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                        But avoid



                                                                        • Asking for help, clarification, or responding to other answers.

                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                        To learn more, see our tips on writing great answers.




                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function () {
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14093020%2fbackup-mysql-database-with-codeigniter%23new-answer', 'question_page');
                                                                        }
                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        Popular posts from this blog

                                                                        Xamarin.iOS Cant Deploy on Iphone

                                                                        Glorious Revolution

                                                                        Dulmage-Mendelsohn matrix decomposition in Python