#native_company# #native_desc#
#native_cta#

Simple MySQL Database backup

By Kevin Kinsey
on May 16, 2005

Version: 0.1

Type: Full Script

Category: File Management

License: BSD License

Description: Short, configurable PHP script uses system utilities to back up all MySQL databases to a location you select. Tested on Unix-like systems.

<?php

/********************************************************
*   SIMPLE DATABASE BACKUP, by "dalecosp"		*
*		(c) 2005				*
*	USE AT YOUR OWN RISK!				*
*     ABSOLUTELY NO WARRANTY OF ANY KIND!		*
*							*
* BSD/Pizza license: BSD license, plus: if you  	*
* use this, and we meet, _ you_buy_the_pizza!_		*
*							*
* For additional license terms & important disclaimers,	*
* see the FreeBSD /COPYRIGHT file.			*
********************************************************/

// The system's rename command; we are on UNIX, so it's "mv"...
   $mv="/bin/mv";
   check($mv,"rename utility");

// our backup program ... we'll use mysqldump
   $cmd="/usr/local/bin/mysqldump";
   check($cmd,"database backup utility");

// our compression/zip program ... we use bzip2
   $zip="/usr/bin/bzip2";
   check($zip, "file compression utility");
   $zipext="bz2";

// path to our "backup" location ... mine's on a different disk; this
// could be an NFS mount on another server, a tape drive, DVD-R, whatever...
   $backpath="/home/me/dbbackup";
   check($backpath,"backup directory");

// data for MySQL connection
   $dbhost="dbhost";
   $dbuser="dbuser";
   $dbpass="dbpass";

// function check() makes sure we have the tools...

   function check($program, $type) {
      if (!file_exists($program)) {
        die("$type not found!");
      }
   }

// connect to database
   $conn=mysql_connect("$dbhost", "$dbuser", "$dbpass");

   if ($conn) {
      // get list of databases ...

      $dbs=mysql_query("show databases");

      // loop over the list of databases; move yesterday's to *old.$zipext
      // dump the database today, and zip it up...

      while ($thisdb=mysql_fetch_array($dbs)) {
         $db=$thisdb['Database'];
         system("$mv $backpath/$db.sql.$zipext $backpath/$db.sql.old.$zipext");
         system("$cmd $db > $backpath/$db.sql");
         system("$zip $backpath/$db.sql");
      }
      $msg="Databases backed up to $backpath at ".date('r');
   }
   else {
      $msg="Backup script unable to open database connection!";
   }

   echo $msg;   // The script easily could be made to mail() this to you;
		// I don't care as I run this from cron and it'll mail the output 
		// anyway.  Feel free to "have at it" for the next version :-) 
?>