Using PHP to Backup and Save your MySQL Database
While working on a recent project, i needed to set up a cron job that would run every X amount of hours and backup a database. I’ve done this a few times before, but only this time (while Googling for a better solution) i found David Walsh‘s blog post on how to Backup Your MySQL Database Using PHP. David’s done a great job and i definitely recommend you check his blog out in its entireity for some really neat web dev articles.
I decided to go and put David’s script into class form (my case of OCD is genuine
) and i added one or two things to it. Basically it allows you to backup one or many tables in a database, include or exclude the data from the backup and i also included Rick Ellis’ (of CodeIgniter fame) Zip class to allow you to zip up the backup and stash it somewhere.
Thanks to David Walsh and Rick Ellis!
Here’s the class: DatabaseDump.php
…and here’s how to use it:
$dump = new DatabaseDump("host", "user", "password", "database", "destination/"); $dump->backup();
Be sure to check out the DatabaseDump.php class for the documentation!
| Print article | This entry was posted by Danny Kopping on April 17, 2009 at 3:30 pm, and is filed under MySQL, PHP. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 2 years ago
Why not just define a MySQL backup job and have cron run that when desired?
J.Ja
about 2 years ago
Is the DatabaseDump.php still available? When I click on the above link, I only get a blank page.
Thanks!
about 2 years ago
Hey Justin
Well my primary goal here was to make it so that a) one can process any arbitrary data from the backup (i.e – exclude tables, do some custom logic, flag certain rows etc) and b) to be able to include a MySQL dump as part of a cron job that does various other things. I’m not a fan of defining many cron jobs… It’s too much of a ball-ache to manage.
It might be a little backward or counter-intuitive in some situations, but i just thought it’d be nice to know how to do it through PHP as opposed to using mysqldump straight…
about 2 years ago
Hey Darren
Thanks for pointing this out… Something weird has been happening lately with my webserver. You can access the file here now. I have also updated the post to point to a working file. I’ve had to rename the PHP file to DatabaseDump.php.txt for the server to serve it correctly. Hope you find it useful
Thanks!