How to use mysqldump.exe to backup a MySQL database on Windows
The directory structure intended: c:\backup\mysql\$db\2007-12-25.sql
If not found, an attempt will be made to create c:\backup\mysql\$db\
Dump data to .SQL file
Compress the .SQL file into a .GZ archive
Delete the .SQL file if a .GZ archive is successfully created
<?php
function mysql_dump($db, $un, $pw, $outfile)
{
$command_line = 'c:\\apache\\mysql\\bin\\mysqldump.exe';
$command_line .= ' --user='.$un;
$command_line .= ' --password='.$pw;
$command_line .= ' --complete-insert';
$command_line .= ' --add-drop-table';
$command_line .= ' '.$db.' > '.$outfile;
return shell_exec($command_line);
};
function compress($source, $archive)
{
if(!$fh = fopen($source, 'r')){
die('Open failed for '.$source);
}
if(!$data = file_get_contents($source)){
die('Read failed for '.$source);
}
if(!fclose($fh)){
die('Close failed for '.$source);
}
if(!$zp = gzopen($archive, 'w9')){
die('gzopen failed for '.$archive);
}
if(!gzwrite($zp, $data)){
die('gzwrite failed for '.$zp);
}
if(!gzclose($zp)){
die('gzclose failed for '.$zp);
}
return true;
};
$un = 'username';
$pw = 'password';
$dbs = array('customers', 'employees', 'vendors');
foreach($dbs as $db){
// $outfile will be appended below
$outfile = 'c:\\backup\\mysql\\'.$db;
if(!is_dir($outfile)){
if(mkdir($outfile, 0777)){
echo '<p>Creating '.$outfile.'</p>'."\n";
}else{
echo '<p>Cannot create '.$outfile.'</p>'."\n";
exit;
}
}
$outfile .= '\\'.date('Y-m-d').'.sql';
// Can shell_exec() can be tested for success???
mysql_dump($db, $un, $pw, $outfile);
if(!is_readable($outfile)){
echo "\n".'<p>Cannot locate '.$outfile.'</p>';
}else{
$archive = $outfile.'.gz';
if(!compress($outfile, $archive)){
echo "\n".'<p>Cannot move '.$outfile.' to '.$archive.'</p>';
}else{
echo "\n".'<p>'.$outfile.'<br> --> '.$archive.'</p>';
unlink($outfile);
}
}
}
?>