使用php将mysql数据库下载为sql文件 [英] download mysql database as sql file using php

查看:224
本文介绍了使用php将mysql数据库下载为sql文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站管理面板中,有一个用于备份数据库的选项.为此,我使用以下代码,但无法使用此代码下载数据库.有谁知道这是怎么回事. 我试图回显$return变量,并且其输出正确,但是我无法将文件下载为sql.

In my website admin panel there is an option to take backup of database. For that I use the below code but I can't download db using this code. Did any one know how this happen. I tried to echo the $return variable and its outputs are correct but i cant download the file as sql.

<?php

backup_tables('localhost','root','','dbname');


/* 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)
  {
    $return="";
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);
    //print_r($num_fields);exit;
    $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] = preg_replace("\n","\\n",$row[$j]);

          $row[$j] = preg_replace("/(\n){2,}/", "\\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+');
 // print_r($handle);exit;
  fwrite($handle,$return);
  fclose($handle);

}
?>

推荐答案

//save file
  $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
 // print_r($handle);exit;
  fwrite($handle,$return);
  fclose($handle);
//add below code to download it as a sql file
Header('Content-type: application/octet-stream');
Header('Content-Disposition: attachment; filename=db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql');
echo $return;

这篇关于使用php将mysql数据库下载为sql文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆