Shawn
Shawn

Reputation: 1675

Auto Backup MySQL database with CodeIgniter

I have created a backup option on Codeigniter project. Now I want to the backup database automatically each day with a fixed time.

Here is my backup code:

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

    $backup =& $this->dbutil->backup($prefs); 
    $db_name = "backup_on_" . date("d_m_Y_h_i_s_a") . ".zip";
    $save = 'uploads/dbbackup/'.$db_file_name;
    $this->load->helper('file');
    write_file($save, $backup); 
    $this->load->helper('download');
    force_download($db_name, $backup);
}

Is there any specific query to backup automatically?

Upvotes: 0

Views: 2645

Answers (2)

Akshay Hegde
Akshay Hegde

Reputation: 16997

Why don't you just use crontab and mysqldump to take backup at desired time, there is actually no need to use dbutil class, mysqldump will be faster and reliable compare to dbutil class.

If you read source code of mysqli_utility, _backup method, you will understand how it affects performance.

Say example to take backup everyday at 14:30

crontab -e

Make a entry like below

30 14 * * * /usr/bin/mysqldump --user=USER --password=PASSWORD --databases DBNAME1 DBNAME2 | gzip > /home/someuser/backup.$(date +"%d_%m_%Y_%H_%M_%S").sql.gz

Save crontab

Upvotes: 2

Hasta Dhana
Hasta Dhana

Reputation: 4719

If you have it on a live server, you could setup a cron jobs to call the php file. If you want to set it up locally then you could use something like task scheduler of the corresponding operating system to call the php script followed by the url as the argument. Or you could make a bat file and add it on a scheduler, contains something like :

php 'path/to/project/index.php' dbbackup

If you are using live server, you could open up the cron table by using this command on the terminal :

crontab -e

Then add an entry to make a schedule to suits your needs,
each line of the crontab file takes six arguments, which are, in order:

  • minutes (0 to 59)
  • hours (0 to 23)
  • day of month (1 to 31)
  • month (1 to 12)
  • day of week (0 – 6)
  • command (command to be executed)

Example :

0 13 * * * php [application_path]/index.php dbbackup

Upvotes: 0

Related Questions