backup mysql tables with php

给你一囗甜甜゛ 提交于 2019-12-06 09:06:32

问题


I would like to backup tables (with PHP) from a db if the table prefix is matching with a sub string. What I was trying and is not working

error_reporting(1);
$dbname = 'wp_dev';

if (!mysql_connect('127.0.0.1', 'root', '')) {
    echo 'Connection Error';
    exit;
}

$sql = "SHOW TABLES FROM $dbname LIKE 'wp_%'";
$result = mysql_query($sql);

if (!$result) {
    echo "DB tables could not be listed\n";
    echo 'MySQL Fehler: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_row($result)) {
    echo "<pre>Table: {$row[0]}\n</pre>";
    system( 'mysqldump $dbname $row[0] > verlag_$row[0].sql');
}

mysql_free_result($result);

回答1:


Here is a function for making bakups from db or only some tables

function &backup_tables($host, $user, $pass, $name, $tables = '*'){
  $data = "\n/*---------------------------------------------------------------".
          "\n  SQL DB BACKUP ".date("d.m.Y H:i")." ".
          "\n  HOST: {$host}".
          "\n  DATABASE: {$name}".
          "\n  TABLES: {$tables}".
          "\n  ---------------------------------------------------------------*/\n";
  $link = mysql_connect($host,$user,$pass);
  mysql_select_db($name,$link);
  mysql_query( "SET NAMES `utf8` COLLATE `utf8_general_ci`" , $link ); // Unicode

  if($tables == '*'){ //get all of the 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);
  }

  foreach($tables as $table){
    $data.= "\n/*---------------------------------------------------------------".
            "\n  TABLE: `{$table}`".
            "\n  ---------------------------------------------------------------*/\n";           
    $data.= "DROP TABLE IF EXISTS `{$table}`;\n";
    $res = mysql_query("SHOW CREATE TABLE `{$table}`", $link);
    $row = mysql_fetch_row($res);
    $data.= $row[1].";\n";

    $result = mysql_query("SELECT * FROM `{$table}`", $link);
    $num_rows = mysql_num_rows($result);    

    if($num_rows>0){
      $vals = Array(); $z=0;
      for($i=0; $i<$num_rows; $i++){
        $items = mysql_fetch_row($result);
        $vals[$z]="(";
        for($j=0; $j<count($items); $j++){
          if (isset($items[$j])) { $vals[$z].= "'".mysql_real_escape_string( $items[$j], $link )."'"; } else { $vals[$z].= "NULL"; }
          if ($j<(count($items)-1)){ $vals[$z].= ","; }
        }
        $vals[$z].= ")"; $z++;
      }
      $data.= "INSERT INTO `{$table}` VALUES ";      
      $data .= "  ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
    }
  }
  mysql_close( $link );
  return $data;
}

How to use:

// create backup
//////////////////////////////////////

$backup_file = 'db-backup-'.time().'.sql';

// get backup
$mybackup = backup_tables("myhost","mydbuser","mydbpasswd","mydatabase","*");

// save to file
$handle = fopen($backup_file,'w+');
fwrite($handle,$mybackup);
fclose($handle);

You can modify the line:

$result = mysql_query("SHOW TABLES");

for the table präfix




回答2:


Excellent. Thanks. Made a few minor changes so I can do one table, two or more tables. Use as is for ALL tables.

For ONE table $mybackup = backup_tables("host_name","user_name","password","database_name","table_name");

more TWO or more tables $mybackup = backup_tables("host_name","user_name","password","database_name","table_name1,table_name2,etc");

Then use this function &backup_tables($host, $user, $pass, $name, $tables)




回答3:


and with poo

<?php
//backup
//function &backup_tables($host, $user, $pass, $name, $tables = '*'){

function &backup_tables($host, $user, $pass, $name, $tables){   
$data = "\n/*---------------------------------------------------------------".
      "\n  SQL DB BACKUP ".date("d.m.Y H:i")." ".
      "\n  HOST: {$host}".
      "\n  DATABASE: {$name}".
      "\n  TABLES: {$tables}".
      "\n  ---------------------------------------------------------------*/\n";
 include "connexion.php";

$myquery="SET NAMES `utf8` COLLATE `utf8_general_ci`";
$result = $mylink->query($myquery);

if($tables == '*'){ //get all of the tables
$tables = array();
$myquery="SHOW TABLES";
$result = $mylink->query($myquery);

while($row = mysqli_fetch_row($result)){
  $tables[] = $row[0];
}
}else{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}

foreach($tables as $table){
$data.= "\n/*---------------------------------------------------------------".
        "\n  TABLE: `{$table}`".
        "\n  ---------------------------------------------------------------*/\n";           
$data.= "DROP TABLE IF EXISTS `{$table}`;\n";

$myquery="SHOW CREATE TABLE `{$table}`";
$result = $mylink->query($myquery);

$row = $result->fetch_row();
$data.= $row[1].";\n";

$myquery="SELECT * FROM `{$table}`";
$result = $mylink->query($myquery);
$num_rows = $result->num_rows;


if($num_rows>0){
  $vals = Array(); $z=0;
  for($i=0; $i<$num_rows; $i++){
    $items = mysqli_fetch_row($result);
    $vals[$z]="(";
    for($j=0; $j<count($items); $j++){
      if (isset($items[$j])) { $vals[$z].= "'".$mylink->real_escape_string($items[$j]) ."'"; } else { $vals[$z].= "NULL"; }
      if ($j<(count($items)-1)){ $vals[$z].= ","; }
    }
    $vals[$z].= ")"; $z++;
  }
  $data.= "INSERT INTO `{$table}` VALUES ";      
  $data .= "  ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
  }
  }
 $mylink->close();
 return $data;
 }


//***********
// called by :

$backup_file = 'db-backup-'.time().'.sql';

// get backup

$host = "yourhost";
$user = "youruser";
$pass = "your_pw";
$name = "your base";
$tables= 'your_table';
 $mybackup = backup_tables($host,$user,$pass,$name,$tables);

// save to file
$handle = fopen($backup_file,'w+');
fwrite($handle,$mybackup);
fclose($handle);

//affichage des résultats, pour savoir si la modification a marchée:
 echo("La sauvegarde à été correctement effectuée") ;

?>

where connection.php is :
<?php
 $mylink = new mysqli("host", "user", "pw", "base");
if ($mylink->connect_errno) {
echo "Echec lors de la connexion à MySQL : " . $mylink->connect_error;
exit();
} 



回答4:


I set up simple functions 'openDb()' and get($SQL) to open databases and execute PHP mysql queries. There may be instances where the row by row copy is more useful but you can also use, if it works (using my simple functions above):

 openDb($db,$user,$pw);
 get("CREATE TABLE `TABLE1_backup` LIKE `TABLE1`");
 get("INSERT INTO `TABLE1_backup` (SELECT * FROM `TABLE1`)");

(NB This is a skeletal description. Add DROPs etc as needed. The 'get' returns T/F depending on success so for debugging it may be necessary to test for false and provide the MySQLi_ERROR)




回答5:


//change to the function provided by markus to support new php versions:
function &backup_tables($host, $user, $pass, $name, $tables = '*'){
  $data = "\n/*---------------------------------------------------------------".
          "\n  SQL DB BACKUP ".date("d.m.Y H:i")." ".
          "\n  HOST: {$host}".
          "\n  DATABASE: {$name}".
          "\n  TABLES: {$tables}".
          "\n  ---------------------------------------------------------------*/\n";

  $link = mysqli_connect($host,$user,$pass);
  mysqli_select_db($link,$name);
  mysqli_query( $link,"SET NAMES `utf8` COLLATE `utf8_general_ci`" ); // Unicode

  if($tables == '*'){ //get all of the tables
    $tables = array();
    $result = mysqli_query($link, "SHOW TABLES");
    while($row = mysqli_fetch_row($result)){
      $tables[] = $row[0];
    }
  }else{
    $tables = is_array($tables) ? $tables : explode(',',$tables);
  }

  foreach($tables as $table){
    $data.= "\n/*---------------------------------------------------------------".
            "\n  TABLE: `{$table}`".
            "\n  ---------------------------------------------------------------*/\n";           
    $data.= "DROP TABLE IF EXISTS `{$table}`;\n";

    $res = mysqli_query($link, "SHOW CREATE TABLE `{$table}`");
    $row = mysqli_fetch_row($res);
    $data.= $row[1].";\n";

    $result = mysqli_query($link, "SELECT * FROM `{$table}`");
    $num_rows = mysqli_num_rows($result);    

    if($num_rows>0){
      $vals = Array(); $z=0;
      for($i=0; $i<$num_rows; $i++){
        $items = mysqli_fetch_row($result);
        $vals[$z]="(";
        for($j=0; $j<count($items); $j++){
          if (isset($items[$j])) { $vals[$z].= "'".mysqli_real_escape_string($link, $items[$j])."'"; } else { $vals[$z].= "NULL"; }
          if ($j<(count($items)-1)){ $vals[$z].= ","; }
        }
        $vals[$z].= ")"; $z++;
      }
      $data.= "INSERT INTO `{$table}` VALUES ";      
      $data .= "  ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
    }
  }
  mysqli_close( $link );
  return $data;
}



回答6:


function backup_tables($tables = '*', $filepath) {
$data = "\n/*---------------------------------------------------------------" .
        "\n  SQL DB BACKUP " . date("d.m.Y H:i") . " " .
        "\n  HOST: {$host}" .
        "\n  DATABASE: {$name}" .
        "\n  TABLES: {$tables}" .
        "\n  ---------------------------------------------------------------*/\n";
mysql_query("SET NAMES `utf8` COLLATE `utf8_general_ci`"); // Unicode

if ($tables == '*') { //get all of the tables
    $tables = array();
    $result = mysql_query("SHOW TABLES");
    while ($row = mysql_FetchRecordsFromCSV_row($result)) {
        $tables[] = $row[0];
    }
} else {
    $tables = is_array($tables) ? $tables : explode(',', $tables);
}

foreach ($tables as $table) {
    $data.= "\n/*---------------------------------------------------------------" .
            "\n  TABLE: `{$table}`" .
            "\n  ---------------------------------------------------------------*/\n";
    $data.= "DROP TABLE IF EXISTS `{$table}`;\n";
    $res = mysql_query("SHOW CREATE TABLE `{$table}`");
    $row = mysql_fetch_row($res);
    $data.= $row[1] . ";\n";

    $result = mysql_query("SELECT * FROM `{$table}`");
    $num_rows = mysql_num_rows($result);

    if ($num_rows > 0) {
        $vals = Array();
        $z = 0;
        for ($i = 0; $i < $num_rows; $i++) {
            $items = mysql_fetch_row($result);
            $vals[$z] = "(";
            for ($j = 0; $j < count($items); $j++) {
                if (isset($items[$j])) {
                    $vals[$z].= "'" . mysql_real_escape_string($items[$j]) . "'";
                } else {
                    $vals[$z].= "NULL";
                }
                if ($j < (count($items) - 1)) {
                    $vals[$z].= ",";
                }
            }
            $vals[$z].= ")";
            $z++;
        }
        $data.= "INSERT INTO `{$table}` VALUES ";
        $data .= "  " . implode(";\nINSERT INTO `{$table}` VALUES ", $vals) . ";\n";
    }
}
//mysql_close( $link );
$handle = fopen($filepath, 'w+');
fwrite($handle, $data);
fclose($handle);

}



来源:https://stackoverflow.com/questions/13659534/backup-mysql-tables-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!