CrankBerry Blog Title

No Comments

Automated MySQL database backup with PHP and cronjob

At some point of working on your website you'll want to back up you MySQL database. This is they key for all of you building dynamic sites. If one day your server goes down or something you may have the files backed up but without the database you'll have to start from scratch again. If you operate a very slow-paced site then manual back up is fine but if you want to backup your database daily then it becomes tedious. I, myself is lazy so I came up with a PHP and Cronjob solution to automatically backup MySQL database.

Automating It

What you need? The first thing you need to know how to do it set cronjobs. If you don't know how to do that you can learn how to set cronjobs here. The cronjob is what will automate your server to run the script and how often to run it.

The Files

All you'll need is two files to make this work. The first file, mysqldump.php can be grabbed from The next thing you need is my backup.php file. Just create a file called backup.php and dump the following script inside.


//The File Name You Want To Use
$fileName = 'Filename';

$sqlhost = 'localhost';
$sqluser = 'db_user';
$sqlpass = 'db_password';
$sqldb = 'db_name';

//You Don't Need to Edit This

//Today's Timestamp
$today_ts = strtotime("now");

$backupDate = date('y.m.d.h.i', $today_ts);
$backupFile =  $backupDate.'- '.$fileName.'.txt';

//Connect to mysql server
$connessione = @mysql_connect($sqlhost,$sqluser,$sqlpass);

//Include class

//Create new instance of MySQLDump
$dumper = new MySQLDump($sqldb);

//If you want to write the MySQL dump to file


The Setup

Configure the first file variables of the script and then just leave the rest. Put the backup.php and mysqldump.php in the same folder where you want the back up files to be dumped. Set the cronjob to run backup.php you don't need to worry about mysqldump.php. That's it, it'll automatically backup.

Possible Problems

The problems that you may experience is the MySQL privileges. If your account doesn't have enough privilege then you may not be able to properly query the database. Another problem maybe the CHMOD of the folder you're backing up to. You need to have write access into that folder.

Recovering from Backup

To recover you database just log into your phpMyAdmin, open the database you want to recover. Select the import tab and just browse for the file. If I recall the file itself should overwrite tables that are already in place if not then you may have to drop all the tables first.

Tags: , ,

This entry was posted on Friday, April 16th, 2010 at 5:04 pm and is filed under PHP, Tools, Web Owners. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply

Spam protection by WP Captcha-Free