To import or export MySQL dumps, we can use mysql and mysqldump commands. Let’s call them from PHP.
<?php
// Import and export MySQL dump in PHP, using mysql client command line tools
// (c) 2006, Sébastien Santoro aka Dereckson, released in public domain
//Connections info (of course we'll use config.php or something variables, this is a sample)
$sql['host'] = "localhost";
$sql['login'] = "root";
$sql['pass'] = "";
$sql['database'] = "MySiteDatabase";
//Import a dump from a file
function import_dump (string $pathFile) {
global $sql;
system("mysql -h$sql[host] -u$sql[login] -p$sql[pass] $sql[database] < " + $pathfile);
}
//Import a dump from a string
function import_dump_string (string $dump) {
global $sql;
$handle = popen("mysql -h$sql[host] -u$sql[login] -p$sql[pass] $sql[database]", "w");
if (fwrite($handle, $dump) === FALSE) {
//We've an error (not a sql error in our dump, but the process mysql isn't correctly opened)
}
pclose($handle);
}
//Export our database and returns dump filename
//Optionally, we can specify one or more tables to export (if not specified, all the database will be dumped)
function export_dump ($tables = '') {
global $sql;
$filename = $sql['database'] . '.' . time() . '.sql';
system("mysqldump -h$sql[host] -u$sql[login] -p$sql[pass] $sql[database] $tables > $filename");
return $filename;
}
?>
Dump the database and provide download link :
<?php
//Dump our database in whole in a file :
$dumpFile = export_dump();
//Link
echo "<a href='$dumpFile'>Download the backup of the $sql[database] database</a>";
?>
Execute posted dump :
<?php
//Dump our database in whole in a file :
import_dump_string($_POST[sqldump]);
?>
Of course, on Windows, you’ve to add your MySQL server bin directory in the path or replace system(“mysql …”) by system(“d:WebServerMySQLbinmysql.exe …”);