<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'database user name';
$backup_response = backup_Database($dbhost,$dbuser,$dbpass,$dbname);
if($backup_response) {
echo 'Database Backup Successfully Created!';
}
else {
echo 'Errors in Database Backup Creating!';
}
?>
<?php
function backup_Database($hostName,$userName,$password,$DbName,$tables = '*')
{
// CONNECT TO THE DATABASE
$con = mysql_connect($hostName,$userName,$password) or die(mysql_error());
mysql_select_db($DbName,$con) or die(mysql_error());
// GET ALL TABLES
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = 'SET FOREIGN_KEY_CHECKS=0;' . "rn";
$return.= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "rn";
$return.= 'SET AUTOCOMMIT=0;' . "rn";
$return.= 'START TRANSACTION;' . "rn";
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table) or die(mysql_error());
$num_fields = mysql_num_fields($result) or die(mysql_error());
$data.= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$data.= "nn".$row2[1].";nn";
for ($i = 0; $i<$num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$data.= 'INSERT INTO '.$table.' VALUES(';
for($x=0; $x<$num_fields; $x++)
{
$row[$x] = addslashes($row[$x]);
$row[$x] = clean($row[$x]); // CLEAN QUERIES
if (isset($row[$x])) {
$data.= '"'.$row[$x].'"' ;
} else {
$data.= '""';
}
if ($x<($num_fields-1)) {
$data.= ',';
}
} // end of the for loop 2
$data.= ");n";
} // end of the while loop
} // end of the for loop 1
$data.="nnn";
} // end of the foreach*/
$return .= 'SET FOREIGN_KEY_CHECKS=1;' . "rn";
$return.= 'COMMIT;';
//SAVE THE BACKUP AS SQL FILE
$f_name=$DbName.'-Database-Backup-'.date('Y-m-d @ h-i-s').'.sql';
$handle = fopen($f_name,'w+');
fwrite($handle,$data);
fclose($handle);
if($data)
{
return true;
}
else
return false;
} // end of the function
// CLEAN THE QUERIES
function clean($str) {
if(@isset($str)){
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
else{
return 'NULL';
}
}
?>
database backup is created after call backup_database(...) function.
Now add following code to export in .sql file format.
if($data)
{
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\".$f_name."");
echo $data; exit;
return true;
}
else
return false;
} // end of the function
Now backup file is downloaded successfully
Note: Add this code in admin side only due to database security.
0 Comments