我正在尝试执行php / mysql备份
我从表单页面接收值,然后使用命令“select tables”,我将这些值保存在数组中。
之后我执行“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.' ';
?>
答案 0 :(得分:5)
答案 1 :(得分: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);
}