我想添加一个自定义函数到我正在工作的网站的后端。MySql多表下载与PHP
我有一个MySql数据库与多个表,我希望能够通过单击链接下载。
如果备份文件可以全部添加到zip文件中进行下载,那也是很棒的。
因此,在PHP中,如何创建所有数据库表的副本(最好是SQL格式)并将其压缩下载?
我不确定MySql“INTO OUTFILE”方法是否可用于我的共享主机帐户。 MySql数据库位于与我的网站文件不同的服务器上。
我想添加一个自定义函数到我正在工作的网站的后端。MySql多表下载与PHP
我有一个MySql数据库与多个表,我希望能够通过单击链接下载。
如果备份文件可以全部添加到zip文件中进行下载,那也是很棒的。
因此,在PHP中,如何创建所有数据库表的副本(最好是SQL格式)并将其压缩下载?
我不确定MySql“INTO OUTFILE”方法是否可用于我的共享主机帐户。 MySql数据库位于与我的网站文件不同的服务器上。
试试看看这个代码。一些调试可能需要,但你会明白。
backup_tables('localhost','username','password','blog');
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$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 '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
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] = ereg_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";
}
//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
上面的代码也没有使用拉链的,你可以用下面描述的功能。
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
我可能直到今天晚些时候才开始测试,但会让你知道它是如何发展的。 – 2012-04-14 06:31:53
您发布的第一个代码有效,现在我可以获取我的表格副本。还没有尝试过第二部分呢。 – 2012-04-14 06:39:52
两部分工作完美,谢谢! – 2012-04-14 06:51:20
您是否试过INTO OUTFILE方法?如果没有,你有通过PHP访问命令行上的mysqldump吗? – liquorvicar 2012-04-14 07:13:27