-1

我正在尝试执行 php/mysql 备份

我从表单页面接收值,然后使用“选择表”命令,将这些值保存在数组中。

之后我做了一个“for”循环来备份每个表:

<?php

$dbname = $_POST['txt_db_name'];
$tbname = $_POST['txt_tb_name'];

$ligacao=mysql_connect('localhost','root','')
or die ('Problemas na ligação ao Servidor de MySQL');

$res = mysql_query("SHOW TABLES FROM pessoal");

$tables = array();

mysql_select_db($dbname,$ligacao);

while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$tables[] = "$row[0]";
}

$length = count($tables);


for ($i = 0; $i < $length; $i++) {
$query=
"SELECT * INTO OUTFILE 'pessoa_Out.txt'".
"FIELDS TERMINATED BY ',' ".
"ENCLOSED BY '\"'".
"LINES TERMINATED BY '#'".
"FROM $tables[$i]";


 $resultado = mysql_query($query,$ligacao);

 }



 mysql_close();

 if ($resultado) 
 $msg ='Sucesso na Exportaçao da Database '.$dbname.' ';
 else
 $msg ='Erro Impossivel Exportar a Database '.$tbname.' ';

 ?>
4

2 回答 2

5

不要这样做——你正在重新发明现有的工具!

Invokemysqldump是专门为此目的而设计的。

有了适当的权限,您可以使用 PHPsystemexec调用它。

于 2013-03-25T10:50:51.163 回答
1

首先,我同意应该使用 mysqldump 的说法。但是根据您的评论,您只需要使用 php/mysql 来完成教育(或其他)目的,这里是脚本(是的,它重新发明了轮子)。请注意,您应该在上传此文件的文件夹中创建一个备份目录,并允许 Web 服务器对其进行写入:

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('memory_limit','1500M');
set_time_limit(0);

backup_tables('localhost','user','xxxxxxx','xxxxxxxxxx');

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
  //save file
  $handle = gzopen(getcwd() . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'db-backup-'.time().'.sql.gz','w9');

  $link = mysql_connect($host,$user,$pass);
  mysql_select_db($name,$link);

  //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.';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return .= "\n\n".$row2[1].";\n\n";
    gzwrite($handle,$return);
    for ($i = 0; $i < $num_fields; $i++) 
    {
      while($row = mysql_fetch_row($result))
      {
        $return = 'INSERT INTO '.$table.' VALUES(';
        for($j=0; $j<$num_fields; $j++) 
        {
          $row[$j] = addslashes($row[$j]);
          $row[$j] = str_replace("\n","\\n",$row[$j]);
          if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
          if ($j<($num_fields-1)) { $return.= ','; }
        }

        $return.= ");\n";
        gzwrite($handle,$return);
      }
    }
    $return ="\n\n\n";
    gzwrite($handle,$return);
  }


  gzclose($handle);
}
于 2013-03-25T10:58:29.070 回答