Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I've build a php/mysql (wamp) application and deployed on a local workstation.
My customer wants to save db and restore it when he likes.
I've found this code for saving:
<?php
$DB_HOST = "localhost";
$DB_USER = "root";
$DB_PASS = "admin";
$DB_NAME = "dbname";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$tables = array();
$result = mysqli_query($con,"SHOW TABLES");
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($con, "SELECT * FROM ".$table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));
$return .= "\n\n".$row2[1].";\n\n";
for ($i=0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO '.$table.' VALUES(';
for ($j=0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"'.$row[$j].'"';} else { $return .= '""';}
if($j<$num_fields-1){ $return .= ','; }
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$handle = fopen('backup.sql', 'w+');
fwrite($handle, $return);
fclose($handle);
echo "success";
?>
This code saves file in a default folder.
What I need is to let user to decide where to save backup file or simply download it through browser.
On the other hand user needs to restore from the file he wants so I need a 'browse' button to let him choose the file in any of his folder.
My database is utf8_general_ci and has english, french and italian language I don't need complex codes because I wouldn't know how to manage them :-(
Thanks in advance.
Best way to export database using php script.
Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "Your Username";
$mysqlPassword = "Your Password";
$mysqlHostName = "Your Host";
$DbName = "Your Database Name here";
$backup_name = "mybackup.sql";
$tables = "Your tables";
//or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit;
}
?>
This tool might be useful, it's a pure PHP based export utility: https://github.com/2createStudio/shuttle-export
Try the following.
Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>
To restore the backup you just need to run LOAD DATA INFILE query like this:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'yourtable.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>
In *nix systems, use the WHICH command to show the location of the mysqldump, try this :
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'test';
$mysqldump=exec('which mysqldump');
$command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $dbname.sql";
exec($command);
?>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";
mysql_close($conn);
?>
Here is my code, This will backup MySQL database and store it in the specified path.
<?php
function backup_mysql_database($options){
$mtables = array(); $contents = "-- Database: `".$options['db_to_backup']."` --\n";
$mysqli = new mysqli($options['db_host'], $options['db_uname'], $options['db_password'], $options['db_to_backup']);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$results = $mysqli->query("SHOW TABLES");
while($row = $results->fetch_array()){
if (!in_array($row[0], $options['db_exclude_tables'])){
$mtables[] = $row[0];
}
}
foreach($mtables as $table){
$contents .= "-- Table `".$table."` --\n";
$results = $mysqli->query("SHOW CREATE TABLE ".$table);
while($row = $results->fetch_array()){
$contents .= $row[1].";\n\n";
}
$results = $mysqli->query("SELECT * FROM ".$table);
$row_count = $results->num_rows;
$fields = $results->fetch_fields();
$fields_count = count($fields);
$insert_head = "INSERT INTO `".$table."` (";
for($i=0; $i < $fields_count; $i++){
$insert_head .= "`".$fields[$i]->name."`";
if($i < $fields_count-1){
$insert_head .= ', ';
}
}
$insert_head .= ")";
$insert_head .= " VALUES\n";
if($row_count>0){
$r = 0;
while($row = $results->fetch_array()){
if(($r % 400) == 0){
$contents .= $insert_head;
}
$contents .= "(";
for($i=0; $i < $fields_count; $i++){
$row_content = str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));
switch($fields[$i]->type){
case 8: case 3:
$contents .= $row_content;
break;
default:
$contents .= "'". $row_content ."'";
}
if($i < $fields_count-1){
$contents .= ', ';
}
}
if(($r+1) == $row_count || ($r % 400) == 399){
$contents .= ");\n\n";
}else{
$contents .= "),\n";
}
$r++;
}
}
}
if (!is_dir ( $options['db_backup_path'] )) {
mkdir ( $options['db_backup_path'], 0777, true );
}
$backup_file_name = $options['db_to_backup'] . " sql-backup- " . date( "d-m-Y--h-i-s").".sql";
$fp = fopen($options['db_backup_path'] . '/' . $backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
echo "Backup file created '--$backup_file_name' ($result)";
}
fclose($fp);
return $backup_file_name;
}
$options = array(
'db_host'=> 'localhost', //mysql host
'db_uname' => 'root', //user
'db_password' => '', //pass
'db_to_backup' => 'attendance', //database name
'db_backup_path' => '/htdocs', //where to backup
'db_exclude_tables' => array() //tables to exclude
);
$backup_file_name=backup_mysql_database($options);
If you dont have phpMyAdmin, you can write in php CLI commands such as login to mysql and perform db dump. In this case you would use shell_exec function.
I would Suggest that you do the folllowing,
<?php
function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
$mysqli = new mysqli($host, $user, $pass, $name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while ($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if ($tables !== false)
{
$target_tables = array_intersect($target_tables, $tables);
}
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;\r\n/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;\r\n/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--Database: `" . $name . "`\r\n\r\n\r\n";
foreach ($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM ' . $table);
$fields_amount = $result->field_count;
$rows_num = $mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE ' . $table);
$TableMLine = $res->fetch_row();
$content .= "\n\n" . $TableMLine[1] . ";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0)
{
while ($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter % 100 == 0 || $st_counter == 0)
{
$content .= "\nINSERT INTO " . $table . " VALUES";
}
$content .= "\n(";
for ($j = 0; $j < $fields_amount; $j++)
{
$row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
if (isset($row[$j]))
{
$content .= '"' . $row[$j] . '"';
}
else
{
$content .= '""';
} if ($j < ($fields_amount - 1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
} $st_counter = $st_counter + 1;
}
} $content .="\n\n\n";
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;";
$backup_name = $backup_name ? $backup_name : $name . "___(" . date('H-i-s') . "_" . date('d-m-Y') . ")__rand" . rand(1, 11111111) . ".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
echo $content;
exit;
}
?>
The enitre project for export and import can be found at https://github.com/tazotodua/useful-php-scripts.
I would Suggest that you do the folllowing,
<?php
$con = mysqli_connect('HostName', 'UserName', 'Password', 'DatabaseName');
$tables = array();
$result = mysqli_query($con,"SHOW TABLES");
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($con, "SELECT * FROM ".$table);
$num_fields = mysqli_num_fields($result);
$return .= 'DROP TABLE '.$table.';';
$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));
$return .= "\n\n".$row2[1].";\n\n";
for ($i=0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO '.$table.' VALUES(';
for ($j=0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"'.$row[$j].'"';} else { $return .= '""';}
if($j<$num_fields-1){ $return .= ','; }
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$handle = fopen('backup.sql', 'w+');
fwrite($handle, $return);
fclose($handle);
echo "success";
?>
upd. fixed error in code, added space before VALUES in line $return .= 'INSERT INTO '.$table.'VALUES(';
You can use this command it works or me 100%
exec('C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -uroot DatabaseName> c:\\database_backup.sql');
note:
C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe is the path for mysqldump app , check on your pc.
-uroot is -u{UserName}
If your database is protected with password then add after -uroot this sentense -p{YourPassword}
Related
I need help in doing a php code wherein I can download a backup file of my database upon clicking a button but in my case, the function of my code as of now is just directly downloading it in the Downloads. I would like to browse for a specific path first where I can store the file before downloading it just like when uploading a file. Here is my code:
<?php
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "db_capstone";
$backup_name = "mybackup.sql";
$tables = array("tbl_borrower", "tbl_consumable", "tbl_consumableborrower", "tbl_course", "tbl_damaged", "tbl_damagedreport", "tbl_equip", "tbl_equiprestock", "tbl_notif", "tbl_restock", "tbl_students", "tbl_subject", "tbl_user", "tbl_viewborrower");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit;
}
?>
I haven't tried anything yet because I have no idea on what to do to browse for a specific path before downloading the file.
I am trying to create a function that exports the mysql database. I researched many ways to do that. I have arrived to the function below. The problem with this is the exporting is so slow my database size is only 10mb. Is there a way to make this faster or improve it?
public function backup_database($tables = '*'){
if ($this->databaseConnection()) {
$return = '';
if($tables == '*') {
$tables = array();
$sql = $this->db_connection->prepare('SHOW TABLES');
if($sql->execute()){
while($row = $sql->fetch()){
$tables[] = $row[0];
}
}
}
else {
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table) {
$result = $this->db_connection->prepare('SELECT * FROM ' . $table);
$result->execute();
$num_fields = $result->rowCount();
$return .= 'DROP TABLE ' . $table . ';';
$row2 = $this->db_connection->prepare('SHOW CREATE TABLE '.$table);
$row2->execute();
$row2 = $row2->fetch();
$return .= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++){
while($row = $result->fetch())
{
$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 .= ");\n";
}
}
$return .="\n\n\n";
}
if (!file_exists('database_backups')) {
mkdir('database_backups', 0777, true);
}
$filename = 'database_backups/db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql.gz';
$handle = fopen($filename,'w+');
$gzdata = gzencode($return, 9);
fwrite($handle,$gzdata);
fclose($handle);
return '1';
}
If you want to export all database tables at once, you can just use this php code ---
$backup_file = "/var/www/html/DB_backup/evidyaa" . date("Y-m-d-H-i-s") . '.sql'; //this would the path of the filename for backup
$command = "mysqldump --user=dbuser --password=dbpass --host=dbhost ". "dbname > $backup_file";
passthru($command);
echo 'done';
If you are using windows then command would be
$backup_file = "/var/www/html/DB_backup/evidyaa" . date("Y-m-d-H-i-s") . '.sql'; //this would the path of the filename for backup
$command = "c:\xampp\mysql\bin\mysql.exe --user=dbuser --password=dbpass --host=dbhost ". "dbname > $backup_file";
I try to run a cron job to do a backup to my database.
The problem that the cron job is execute and i receive an email that the cron job is executing but the problem is i don't have a backup file.
But if i run the page on the browser without the cron job i have a back up file.
Also i have a button if i click this button i receive a backup file.
That mean my code work.
Cron job file:
<?php
include("includes/connect.php");
include("includes/functions.php");
include("includes/backup.php");
?>
Backup Function and this function is in functions.php
<?php
function Export_Database($host,$user,$pass,$name,$tables=false,$backup_name=false)
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
$fp = fopen($_SERVER['DOCUMENT_ROOT']."/backup"."/mybackup-".date('d-m-Y')."-".date('H:i:s').".sql","wb");
fwrite($fp,$content);
fclose($fp);
exit();
}?>
Backup page:
<?php
$mysqlUserName = "***";
$mysqlPassword = "";
$mysqlHostName = "****";
$DbName = "****";
$backup_name = "mybackup.sql";
$tables = array();
$showTable = "SHOW TABLES from $DbName";
$getData = mysqli_query($conn, $showTable);
while ($row = mysqli_fetch_row($getData)) {
$tables[] = $row;
}
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
?>
How can i solve this problem to run the code when the cron job is execute??!!
Why don't you use mysqldump?
As it says on the documentation:
4.5.4 mysqldump — A Database Backup Program
[cron-times] mysqldump -u <dbuser> --password <pw> [--host <host] --all-databases > /opt/mysql.bkp/`date`
I want to make a PHP script that will back up my selected tables from a database. From Stack Overflow I found this:
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "test";
$backup_name = "mybackup.sql";
$tables = "msc_market";
//or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content;
}
?>
Now in this code I change the $tables value for selecting a single table or more. For more than one table I put an array with table names. But the problem is that every time I get a full backup of all tables even if I change $tables value every time I get same result. How do I get only a backup of the selected tables? Please help me.
As seen, 5th parameter's value in Export_Database() is overridden by false value when it is called, where you need to pass array of database tables because array_intersect() can filter similar value from array parameters only. Corrected code given below...
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "test";
$backup_name = "mybackup.sql";
$tables = array("msc_market", "mytable1","mytable2","mytable3");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables, $backup_name );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$backup_name = $backup_name ? $backup_name : $name.".sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content;
}
?>
Your problem is that the array_intersect is processing the values, not the keys. Since these are one-dimensional arrays, you need to intersect the keys like this:
$target_tables = array_values(array_intersect(array_keys($target_tables), array_keys($tables)));
Explanation:
Basically you're first changing the arrays into arrays of keys, then intersecting them, and then transforming it back to values.
I get the subj. when I try to make backup of my database in a text file.
function backup_tables($backup_filename, $tables = '*')
{
$conf = new JConfig();
$dbhost = $conf->host;
$dbuser = $conf->user;
$dbpassword = $conf->password;
$dbname = $conf->db;
$link = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbname, $link) or die(mysql_error());
$return = "drop database if exists `$dbname`;\n\ncreate database `$dbname`;\n\nuse `$dbname`;\n\n";
$return .= "/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;\n\n";
$return .= "/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;\n\n";
$return .= "/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;\n\n";
$return .= "/*!40101 SET NAMES utf8 */;\n\n";
$handle = fopen($backup_filename, 'w+');
fwrite($handle, $return); $return = "";
// 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);
}
// cycle through
foreach ($tables as $table) {
$result = mysql_query('SELECT * FROM ' . $table);
$num_fields = mysql_num_fields($result);
$return .= 'DROP TABLE IF EXISTS `' . $table . '`;';
$return .= "\n\n" . mysql_fetch_row(mysql_query('SHOW CREATE TABLE `' . $table . '`;'))[1] . " DEFAULT CHARSET=cp1251;\n\n";
while ($row = mysql_fetch_row($result)) {
$return .= 'INSERT INTO ' . $table . ' VALUES(';
for ($i = 0; $i < $num_fields; $i++) {
$row[$i] = str_replace("\n", "\\n", addslashes($row[$i]));
$return .= '"' . (isset($row[$i])? $row[$i] : '') . '"';
if ($num_fields - $i - 1) {
$return .= ',';
}
}
$return .= ");\n";
fwrite($handle, $return); $return = "";
}
if($return) {
fwrite($handle, $return);
$return .= "\n\n\n";
}
}
fclose($handle);
}
This function works well by the exception that there is an memory leaks somewhere. It creates a file ~30 MiB and hungs with mentioned error. Memory usage of the httpd process increases uniformly while file generation is in progress. And one more: generation hungs at a large table (containing a log), but I think this is no matter 'cause information written row by row.
And one more: generation hungs at a large table (containing a log),
but I think this is no matter 'cause information written row by row.
Actually this is the cause: I should use mysql_unbuffered_query instead mysql_query. Now this function looks like this:
function backup_tables($backup_filename, $tables = '*')
{
$conf = new JConfig();
$dbhost = $conf->host;
$dbuser = $conf->user;
$dbpassword = $conf->password;
$dbname = $conf->db;
$link = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbname, $link) or die(mysql_error());
$return = "drop database if exists `$dbname`;\n\ncreate database `$dbname`;\n\nuse `$dbname`;\n\n";
$return .= "/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;\n\n";
$return .= "/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;\n\n";
$return .= "/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;\n\n";
$return .= "/*!40101 SET NAMES utf8 */;\n\n";
$handle = fopen($backup_filename, 'w+');
fwrite($handle, $return); $return = "";
// 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);
}
// cycle through
foreach ($tables as $table) {
$return .= "DROP TABLE IF EXISTS `$table`;";
$return .= "\n\n" . mysql_fetch_row(mysql_query("SHOW CREATE TABLE `$table`;"))[1] . " DEFAULT CHARSET=cp1251;\n\n";
$result = mysql_unbuffered_query("SELECT * FROM `$table`");
$num_fields = mysql_num_fields($result);
while ($row = mysql_fetch_row($result)) {
$return .= "INSERT INTO `$table` VALUES(";
for ($i = 0; $i < $num_fields; $i++) {
$row[$i] = str_replace("\n", "\\n", addslashes($row[$i]));
$return .= '"' . (isset($row[$i])? $row[$i] : '') . '"';
if ($num_fields - $i - 1) {
$return .= ',';
}
}
$return .= ");\n";
fwrite($handle, $return); $return = "";
}
if($return)
fwrite($handle, $return);
$return = "\n\n\n";
}
fclose($handle);
}
The PHP answer here is to increase your max memory size if not your max execution time at the same time.
Outside of this being an exercise in re-creating the mysqldump command, is there a reason to perform this from within PHP code?
You might be better off using mysqldump or something like Holland http://hollandbackup.org/ to go through and dump each table individually.
Current answer uses a deprecated function. The new way to do this is using mysqli::use_result.
In my case I ran into the exhausted memory error trying to write a large sql table into a file. Here's how I used it.
$conn = new mysqli("localhost", "my_user", "my_password", "my_db");
$sql = 'SELECT row1, row2 from table';
$fp = fopen('output.json', 'w');
if ($conn->multi_query($sql)) {
do {
if ($result = $conn->use_result()) {
while ($row = $result->fetch_row()) {
$row1 = $row[0];
$row2 = $row[1];
$item = array('row1'=>$row1, 'row2'=>$row2);
fwrite($fp, json_encode($item));
}
$result->close();
}
} while ($conn->more_results() && $conn->next_result());
}
fclose($fp);
$conn->close();