0

I'm looking to backup an entire MySQL database to an SQL file from PHP.

Is this possible? I have been searching for a while and haven't found anything.

Thanks.

0

1 Answer 1

1

Other option than using mysql dump

The below is a tested php code to backup database in .sql file

<?php
ini_set("max_execution_time", 0);

$dir = "";//set path of folder where to save file
if(!(file_exists($dir))) {
mkdir($dir, 0777);
}

$host = ""; //host name
$username = ""; //username
$password = ""; // your password
$dbname = ""; // database name

backup_tables($host, $username, $password, $dbname);

function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$con = mysql_connect($host,$user,$pass);
mysql_select_db($name,$con);

//get all of the 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 = "";

//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
//$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n".$row2[1].";\n";

while($row = mysql_fetch_row($result))
{
$return.="\n";
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("#n#","n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");";
}
$return.="\n";
}


date_default_timezone_set('Asia/Kolkata');
//save file
$way=$dir.'backup-'.date('Y-m-d H:i:s').'.sql';
$handle = fopen($way,'w+');
fwrite($handle,$return);
fclose($handle);
echo $way;
}

?>

The above code will create a .sql file in the location you have set in the code.To backup data time to time say in every day you have to hit this php file after each day to do that in:

Linux

Use cronjobs

Windows

Use Windows task Scheduler

Good Luck

Sign up to request clarification or add additional context in comments.

2 Comments

This is slow, uses a deprecated API and doesn't dump any schema information. Why would anyone use this when mysqldump is the tool for the job ? If one just wants to backup data SELECT...INTO OUTFILE and LOAD DATA INFILE will be a whole lot faster.
@HoboSapiens I clearly said in my answer Other option than using mysql dump.And this is a working code I have tried it.This is just my way of doing that .I was just trying to give other options.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.