Search code examples
phpmysqlcodeignitercodeigniter-query-builder

How to back db and truncate all tables in CodeIgniter?


I am using this code to backup data, how to truncate all tables in db?

My function for backupdb

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

How to add truncate code in above function?


Solution

  • 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);
    
        $this->db->truncate('table_name');  //truncate the table.
        
    }
    

    Note:- For More information regarding this

    https://codeigniter.com/userguide3/database/query_builder.html

    SOLUTION ONE

    $this->db->truncate('table_name1');
    $this->db->truncate('table_name2');
    $this->db->truncate('table_name3');
    

    SOLUTION TWO

     function emptytablesbycomma($stringoftables) {
         $array_tablenames = explode(",", $stringoftables);
         if (!empty($array_tablenames)) {
            foreach ($array_tablenames as $tablename) {
                $this->db->truncate($tablename);
            }
         }
     }
    
    $stringoftables='table_name1,table_name2,table_name3';
    $this->emptytablesbycomma($stringoftables);