首页 > 开发 > PHP > 正文

php实现数据库导出或导出成sql文件代码

2024-05-04 22:00:17
字体:大 中 小
来源:转载
供稿:网友

本文章小编是整理了两段不同的代码可以实现数据库导出或导出成sql文件了,下面一起来看看,大家复制保存在指定文件即可.

php实现数据库备份导出成sql

1.首先要得到该数据库中有哪些表,所用函数 mysql_list_tables(),然后可以将获取的所有表名存到一个数组.

2.show create table 表名 可以获取表结构.

3.select * from 表名 取出所有记录,用循环拼接成 insert into... 语句.

php导出sql,导出成的sql语句效果,具体代码:

  1. <?php 
  2.  
  3.  header("Content-type:text/html;charset=utf-8"); 
  4.  
  5.  //配置信息 
  6.  $cfg_dbhost = 'localhost'; 
  7.  $cfg_dbname = 'ftdm'; 
  8.  $cfg_dbuser = 'root'; 
  9.  $cfg_dbpwd = 'root'; 
  10.  $cfg_db_language = 'utf8'; 
  11.  $to_file_name = "ftdm.sql"; 
  12.  // END 配置 
  13.  //链接数据库 
  14.  $link = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd); 
  15.  mysql_select_db($cfg_dbname); 
  16.  //选择编码 
  17.  mysql_query("set names ".$cfg_db_language); 
  18.  //数据库中有哪些表 
  19.  $tables = mysql_list_tables($cfg_dbname); 
  20.  //将这些表记录到一个数组 
  21.  $tabList = array(); 
  22.  while($row = mysql_fetch_row($tables)){ 
  23.   $tabList[] = $row[0]; 
  24.  } 
  25.  
  26.  echo "运行中,请耐心等待...<br/>"; 
  27.  $info = "-- ----------------------------\r\n"; 
  28.  $info .= "-- 日期:".date("Y-m-d H:i:s",time())."\r\n"; 
  29.  $info .= "-- 仅用于测试和学习,本程序不适合处理超大量数据\r\n"; 
  30.  $info .= "-- ----------------------------\r\n\r\n"; 
  31.  file_put_contents($to_file_name,$info,FILE_APPEND); 
  32.  //将每个表的表结构导出到文件 
  33.  foreach($tabList as $val){ 
  34.   $sql = "show create table ".$val; 
  35.   $res = mysql_query($sql,$link); 
  36.   $row = mysql_fetch_array($res); 
  37.   $info = "-- ----------------------------\r\n"; 
  38.   $info .= "-- Table structure for `".$val."`\r\n"; 
  39.   $info .= "-- ----------------------------\r\n"; 
  40.   $info .= "DROP TABLE IF EXISTS `".$val."`;\r\n"; 
  41.   $sqlStr = $info.$row[1].";\r\n\r\n"; 
  42.   //追加到文件 
  43.   file_put_contents($to_file_name,$sqlStr,FILE_APPEND); 
  44.   //释放资源 
  45.   mysql_free_result($res); 
  46.  }  //开源软件:Vevb.com 
  47.  //将每个表的数据导出到文件 
  48.  foreach($tabList as $val){ 
  49.   $sql = "select * from ".$val; 
  50.   $res = mysql_query($sql,$link); 
  51.   //如果表中没有数据,则继续下一张表 
  52.   if(mysql_num_rows($res)<1) continue; 
  53.   // 
  54.   $info = "-- ----------------------------\r\n"; 
  55.   $info .= "-- Records for `".$val."`\r\n"; 
  56.   $info .= "-- ----------------------------\r\n"; 
  57.   file_put_contents($to_file_name,$info,FILE_APPEND); 
  58.   //读取数据 
  59.   while($row = mysql_fetch_row($res)){ 
  60.    $sqlStr = "INSERT INTO `".$val."` VALUES ("; 
  61.    foreach($row as $zd){ 
  62.     $sqlStr .= "'".$zd."', "; 
  63.    } 
  64.    //去掉最后一个逗号和空格 
  65.    $sqlStr = substr($sqlStr,0,strlen($sqlStr)-2); 
  66.    $sqlStr .= ");\r\n"; 
  67.    file_put_contents($to_file_name,$sqlStr,FILE_APPEND); 
  68.   } 
  69.   //释放资源 
  70.   mysql_free_result($res); 
  71.   file_put_contents($to_file_name,"\r\n",FILE_APPEND); 
  72.  } 
  73.  
  74.  echo "OK!"; 
  75.  
  76. ?> 

导入.sql文件到mysql数据库:

  1. <?php 
  2. /** 
  3.  *  
  4.  * ------1. 数据库备份(导出)------------------------------------------------------------ 
  5.  //分别是主机,用户名,密码,数据库名,数据库编码 
  6.  $db = new DBManage ( 'localhost', 'root', 'root', 'test', 'utf8' ); 
  7.  // 参数:备份哪个表(可选),备份目录(可选,默认为backup),分卷大小(可选,默认2000,即2M) 
  8.  $db->backup (); 
  9.  * ------2. 数据库恢复(导入)------------------------------------------------------------ 
  10.  //分别是主机,用户名,密码,数据库名,数据库编码 
  11.  $db = new DBManage ( 'localhost', 'root', 'root', 'test', 'utf8' ); 
  12.  //参数:sql文件 
  13.  $db->restore ( './backup/2014072125.sql'); 
  14.  *---------------------------------------------------------------------- 
  15.  */ 
  16. class DBManage  
  17. { 
  18.  var $db; // 数据库连接 
  19.  var $database; // 所用数据库 
  20.  var $sqldir; // 数据库备份文件夹 
  21.  var $record; 
  22.  // 换行符 
  23.  private $ds = "\n"; 
  24.  // 存储SQL的变量 
  25.  public $sqlContent = ""; 
  26.  // 每条sql语句的结尾符 
  27.  public $sqlEnd = ";"; 
  28.  /** 
  29.   * 初始化 
  30.   * 
  31.   * @param string $host          
  32.   * @param string $username          
  33.   * @param string $password          
  34.   * @param string $thisatabase          
  35.   * @param string $charset          
  36.   */ 
  37.  function __construct($host = 'localhost', $username = 'root', $password = '', $thisatabase = 'test', $charset = 'utf8')  
  38.  { 
  39.   $this->host = $host; 
  40.   $this->username = $username; 
  41.   $this->password = $password; 
  42.   $this->database = $thisatabase; 
  43.   $this->charset = $charset; 
  44.   // 连接数据库 
  45.   $this->db = mysql_connect ( $this->host, $this->username, $this->password ) or die ( "数据库连接失败." ); 
  46.   // 选择使用哪个数据库 
  47.   mysql_select_db ( $this->database, $this->db ) or die ( "无法打开数据库" ); 
  48.   // 数据库编码方式 
  49.   mysql_query ( 'SET NAMES ' . $this->charset, $this->db ); 
  50.  } 
  51.  /* 
  52.   * ------------------------------------------数据库备份start---------------------------------------------------------- 
  53.   */ 
  54.  /** 
  55.   * 数据库备份 
  56.   * 参数:备份哪个表(可选),备份目录(可选,默认为backup),分卷大小(可选,默认2000,即2M) 
  57.   * 
  58.   * @param $string $dir          
  59.   * @param int $size          
  60.   * @param $string $tablename          
  61.   */ 
  62.  function backup($tablename = '', $dir, $size)  
  63.  { 
  64.   $dir = $dir ? $dir : 'backup/'; 
  65.   $size = $size ? $size : 2000; 
  66.   $sql = ''; 
  67.   // 只备份某个表 
  68.   if (! emptyempty ( $tablename ))  
  69.   { 
  70.    echo '正在备份表' . $tablename . '<br />'; 
  71.    // 插入dump信息 
  72.    $sql = $this->_retrieve(); 
  73.    // 插入表结构信息 
  74.    $sql .= $this->_insert_table_structure ( $tablename ); 
  75.    // 插入数据 
  76.    $data = mysql_query ( "select * from " . $tablename ); 
  77.    // 文件名前面部分 
  78.    $filename = date ( 'YmdHis' ) . "_" . $tablename; 
  79.    // 字段数量 
  80.    $num_fields = mysql_num_fields ( $data ); 
  81.    // 第几分卷 
  82.    $p = 1; 
  83.    // 循环每条记录 
  84.    while ( $record = mysql_fetch_array ( $data ) )  
  85.    { 
  86.     // 单条记录 
  87.     $sql .= $this->_insert_record ( $tablename, $num_fields, $record ); 
  88.     // 如果大于分卷大小,则写入文件 
  89.     if (strlen ( $sql ) >= $size * 1000)  
  90.     {  //开源软件:Vevb.com 
  91.      $file = $filename . "_v" . $p . ".sql"; 
  92.      if ($this->_write_file ( $sql, $file, $dir ))  
  93.      { 
  94.       echo "表-" . $tablename . "-卷-" . $p . "-数据备份完成,生成备份文件 <span style='color:#f00;'>$dir$filename</span><br />"; 
  95.      }  
  96.      else  
  97.      { 
  98.       echo "备份表-" . $tablename . "-失败<br />"; 
  99.      } 
  100.      // 下一个分卷 
  101.      $p ++; 
  102.      // 重置$sql变量为空,重新计算该变量大小 
  103.      $sql = ""; 
  104.     } 
  105.    } 
  106.    // sql大小不够分卷大小 
  107.    if ($sql != "")  
  108.    { 
  109.     $filename .= "_v" . $p . ".sql"; 
  110.     if ($this->_write_file ( $sql, $filename, $dir ))  
  111.     { 
  112.      echo "表-" . $tablename . "-卷-" . $p . "-数据备份完成,生成备份文件 <span style='color:#f00;'>$dir$filename</span><br />"; 
  113.     }  
  114.     else  
  115.     { 
  116.      echo "备份卷-" . $p . "-失败<br />"; 
  117.     } 
  118.    } 
  119.   }  
  120.   else  
  121.   { // 备份全部表 
  122.    if ($tables = mysql_query ( "show table status from " . $this->database ))  
  123.    { 
  124.     echo "读取数据库结构成功!<br />"; 
  125.    }  
  126.    else  
  127.    { 
  128.     exit ( "读取数据库结构成功!<br />" ); 
  129.    } 
  130.    // 插入dump信息 
  131.    $sql .= $this->_retrieve(); 
  132.    // 文件名前面部分 
  133.    $filename = date ( 'YmdHis' ) . "_all"; 
  134.    // 查出所有表 
  135.    $tables = mysql_query ( 'SHOW TABLES' ); 
  136.    // 第几分卷 
  137.    $p = 1; 
  138.    // 循环所有表 
  139.    while ( $table = mysql_fetch_array ( $tables ) )  
  140.    { 
  141.     // 获取表名 
  142.     $tablename = $table [0]; 
  143.     // 获取表结构 
  144.     $sql .= $this->_insert_table_structure ( $tablename ); 
  145.     $data = mysql_query ( "select * from " . $tablename ); 
  146.     $num_fields = mysql_num_fields ( $data ); 
  147.     // 循环每条记录 
  148.     while ( $record = mysql_fetch_array ( $data ) )  
  149.     { 
  150.      // 单条记录 
  151.      $sql .= $this->_insert_record ( $tablename, $num_fields, $record ); 
  152.      // 如果大于分卷大小,则写入文件 
  153.      if (strlen ( $sql ) >= $size * 1000)  
  154.      { 
  155.       $file = $filename . "_v" . $p . ".sql"; 
  156.       // 写入文件 
  157.       if ($this->_write_file ( $sql, $file, $dir ))  
  158.       { 
  159.        echo "-卷-" . $p . "-数据备份完成,生成备份文件<span style='color:#f00;'>$dir$file</span><br />"; 
  160.       }  
  161.       else  
  162.       { 
  163.        echo "备份卷-" . $p . "-失败<br />"; 
  164.       } 
  165.       // 下一个分卷 
  166.       $p ++; 
  167.       // 重置$sql变量为空,重新计算该变量大小 
  168.       $sql = ""; 
  169.      } 
  170.     } 
  171.    } 
  172.    // sql大小不够分卷大小 
  173.    if ($sql != "")  
  174.    { 
  175.     $filename .= "_v" . $p . ".sql"; 
  176.     if ($this->_write_file ( $sql, $filename, $dir ))  
  177.     { 
  178.      echo "-卷-" . $p . "-数据备份完成,生成备份文件 <span style='color:#f00;'>$dir$filename<br />"; 
  179.     }  
  180.     else  
  181.     { 
  182.      echo "备份卷-" . $p . "-失败<br />"; 
  183.     } 
  184.    } 
  185.   } 
  186.  } 
  187.  /** 
  188.   * 插入数据库备份基础信息 
  189.   * 
  190.   * @return string 
  191.   */ 
  192.  private function _retrieve() { 
  193.   $value = ''; 
  194.   $value .= '--' . $this->ds; 
  195.   $value .= '-- MySQL database dump' . $this->ds; 
  196.   $value .= '-- Created by DBManage class. ' . $this->ds; 
  197.   $value .= '-- http://www.111cn.net ' . $this->ds; 
  198.   $value .= '--' . $this->ds; 
  199.   $value .= '-- 主机: ' . $this->host . $this->ds; 
  200.   $value .= '-- 生成日期: ' . date ( 'Y' ) . ' 年  ' . date ( 'm' ) . ' 月 ' . date ( 'd' ) . ' 日 ' . date ( 'H:i' ) . $this->ds; 
  201.   $value .= '-- MySQL版本: ' . mysql_get_server_info () . $this->ds; 
  202.   $value .= '-- PHP 版本: ' . phpversion () . $this->ds; 
  203.   $value .= $this->ds; 
  204.   $value .= '--' . $this->ds; 
  205.   $value .= '-- 数据库: `' . $this->database . '`' . $this->ds; 
  206.   $value .= '--' . $this->ds . $this->ds; 
  207.   $value .= '-- -------------------------------------------------------'; 
  208.   $value .= $this->ds . $this->ds; 
  209.   return $value; 
  210.  } 
  211.  /** 
  212.   * 插入表结构 
  213.   * 
  214.   * @param unknown_type $table          
  215.   * @return string 
  216.   */ 
  217.  private function _insert_table_structure($table) { 
  218.   $sql = ''; 
  219.   $sql .= "--" . $this->ds; 
  220.   $sql .= "-- 表的结构" . $table . $this->ds; 
  221.   $sql .= "--" . $this->ds . $this->ds; 
  222.   // 如果存在则删除表 
  223.   $sql .= "DROP TABLE IF EXISTS `" . $table . '`' . $this->sqlEnd . $this->ds; 
  224.   // 获取详细表信息 
  225.   $res = mysql_query ( 'SHOW CREATE TABLE `' . $table . '`' ); 
  226.   $row = mysql_fetch_array ( $res ); 
  227.   $sql .= $row [1]; 
  228.   $sql .= $this->sqlEnd . $this->ds; 
  229.   // 加上 
  230.   $sql .= $this->ds; 
  231.   $sql .= "--" . $this->ds; 
  232.   $sql .= "-- 转存表中的数据 " . $table . $this->ds; 
  233.   $sql .= "--" . $this->ds; 
  234.   $sql .= $this->ds; 
  235.   return $sql; 
  236.  } 
  237.  /** 
  238.   * 插入单条记录 
  239.   * 
  240.   * @param string $table          
  241.   * @param int $num_fields          
  242.   * @param array $record          
  243.   * @return string 
  244.   */ 
  245.  private function _insert_record($table, $num_fields, $record) { 
  246.   // sql字段逗号分割 
  247.   $comma = ""; 
  248.   $insert .= "INSERT INTO `" . $table . "` VALUES("; 
  249.   // 循环每个子段下面的内容 
  250.   for($i = 0; $i < $num_fields; $i ++) { 
  251.    $insert .= ($comma . "'" . mysql_escape_string ( $record [$i] ) . "'"); 
  252.    $comma = ","; 
  253.   } 
  254.   $insert .= ");" . $this->ds; 
  255.   return $insert; 
  256.  } 
  257.  /** 
  258.   * 写入文件 
  259.   * 
  260.   * @param string $sql          
  261.   * @param string $filename          
  262.   * @param string $dir          
  263.   * @return boolean 
  264.   */ 
  265.  private function _write_file($sql, $filename, $dir) { 
  266.   $dir = $dir ? $dir : './backup/'; 
  267.   // 不存在文件夹则创建 
  268.   if (! file_exists ( $dir )) { 
  269.    mkdir ( $dir ); 
  270.   } 
  271.   $re = true; 
  272.   if (! @$fp = fopen ( $dir . $filename, "w+" )) { 
  273.    $re = false; 
  274.    echo "打开文件失败!"; 
  275.   } 
  276.   if (! @fwrite ( $fp, $sql )) { 
  277.    $re = false; 
  278.    echo "写入文件失败,请文件是否可写"; 
  279.   } 
  280.   if (! @fclose ( $fp )) { 
  281.    $re = false; 
  282.    echo "关闭文件失败!"; 
  283.   } 
  284.   return $re; 
  285.  } 
  286.  /* 
  287.   * 
  288.   * -------------------------------上:数据库导出-----------分割线----------下:数据库导入-------------------------------- 
  289.   */ 
  290.  /** 
  291.   * 导入备份数据 
  292.   * 说明:分卷文件格式2014072125.sql 
  293.   * 参数:文件路径(必填) 
  294.   * 
  295.   * @param string $sqlfile          
  296.   */ 
  297.  function restore($sqlfile)  
  298.  { 
  299.   // 检测文件是否存在 
  300.   if (! file_exists ( $sqlfile ))  
  301.   { 
  302.    exit ( "文件不存在!请检查" ); 
  303.   } 
  304.   $this->lock ( $this->database ); 
  305.   // 获取数据库存储位置 
  306.   $sqlpath = pathinfo ( $sqlfile ); 
  307.   $this->sqldir = $sqlpath ['dirname']; 
  308.   // 检测是否包含分卷,将类似2014072125.sql从_v分开,有则说明有分卷 
  309.   $volume = explode ( "_v", $sqlfile ); 
  310.   $volume_path = $volume [0]; 
  311.   echo "请勿刷新及关闭浏览器以防止程序被中止,如有不慎!将导致数据库结构受损<br />"; 
  312.   echo "正在导入备份数据,请稍等!<br />"; 
  313.   if (emptyempty ( $volume [1] ))  
  314.   { 
  315.    echo "正在导入sql:<span style='color:#f00;'>" . $sqlfile . '</span><br />'; 
  316.    // 没有分卷 
  317.    if ($this->_import ( $sqlfile )) { 
  318.     echo "数据库导入成功!"; 
  319.    }  
  320.    else  
  321.    { 
  322.     exit ( '数据库导入失败!' ); 
  323.    } 
  324.   }  
  325.   else  
  326.   { 
  327.    //$volume_id = array(); 
  328.    // 存在分卷,则获取当前是第几分卷,循环执行余下分卷 
  329.    $volume_id = explode ( ".sq", $volume [1] ); 
  330.    // 当前分卷为$volume_id 
  331.    $volume_id = intval ( $volume_id [0] ); 
  332.    while ( $volume_id )  
  333.    { 
  334.     $tmpfile = $volume_path . "_v" . $volume_id . ".sql"; 
  335.     // 存在其他分卷,继续执行 
  336.     if (file_exists ( $tmpfile )) { 
  337.      // 执行导入方法 
  338.      echo "正在导入分卷$volume_id:<span style='color:#f00;'>" . $tmpfile . '</span><br />'; 
  339.      if ($this->_import ( $tmpfile ))  
  340.      { 
  341.      }  
  342.      else  
  343.      { 
  344.       exit ( "导入分卷$volume_id:<span style='color:#f00;'>" . $tmpfile . '</span>失败!可能是数据库结构已损坏!请尝试从分卷1开始导入' ); 
  345.      } 
  346.     }  
  347.     else  
  348.     { 
  349.      echo "此分卷备份全部导入成功!<br />"; 
  350.      return; 
  351.     } 
  352.     $volume_id++; 
  353.    } 
  354.   } 
  355.  } 
  356.  /** 
  357.   * 将sql导入到数据库(普通导入) 
  358.   * 
  359.   * @param string $sqlfile          
  360.   * @return boolean 
  361.   */ 
  362.  private function _import($sqlfile) { 
  363.   // sql文件包含的sql语句数组 
  364.   $sqls = array (); 
  365.   $f = fopen ( $sqlfile, "rb" ); 
  366.   // 创建表缓冲变量 
  367.   $create = ''; 
  368.   while ( ! feof ( $f ) ) { 
  369.    // 读取每一行sql 
  370.    $line = fgets ( $f ); 
  371.    // 如果包含'-- '等注释,或为空白行,则跳过 
  372.    if (trim ( $line ) == '' || preg_match ( '/--*?/', $line, $match )) { 
  373.     continue; 
  374.    } 
  375.    // 如果结尾包含';'(即为一个完整的sql语句,这里是插入语句),并且不包含'ENGINE='(即创建表的最后一句), 
  376.    if (! preg_match ( '/;/', $line, $match ) || preg_match ( '/ENGINE=/', $line, $match )) { 
  377.     // 将本次sql语句与创建表sql连接存起来 
  378.     $create .= $line; 
  379.     // 如果包含了创建表的最后一句 
  380.     if (preg_match ( '/ENGINE=/', $create, $match )) { 
  381.      // 则将其合并到sql数组 
  382.      $sqls [] = $create; 
  383.      // 清空当前,准备下一个表的创建 
  384.      $create = ''; 
  385.     } 
  386.     // 跳过本次 
  387.     continue; 
  388.    } 
  389.    $sqls [] = $line; 
  390.   } 
  391.   fclose ( $f ); 
  392.   // 循环sql语句数组,分别执行 
  393.   foreach ( $sqls as $sql ) { 
  394.    str_replace ( "\n", "", $sql ); 
  395.    if (! mysql_query ( trim ( $sql ) )) { 
  396.     echo mysql_error (); 
  397.     return false; 
  398.    } 
  399.   } 
  400.   return true; 
  401.  } 
  402.  /* 
  403.   * -------------------------------数据库导入end--------------------------------- 
  404.   */ 
  405.  // 关闭数据库连接 
  406.  private function close() { 
  407.   mysql_close ( $this->db ); 
  408.  } 
  409.  // 锁定数据库,以免备份或导入时出错 
  410.  private function lock($tablename, $op = "WRITE") { 
  411.   if (mysql_query ( "lock tables " . $tablename . " " . $op )) 
  412.    return true; 
  413.   else 
  414.    return false; 
  415.  } 
  416.  // 解锁 
  417.  private function unlock() { 
  418.   if (mysql_query ( "unlock tables" )) 
  419.    return true; 
  420.   else 
  421.    return false; 
  422.  } 
  423.  // 析构 
  424.  function __destruct() { 
  425.   mysql_query ( "unlock tables", $this->db ); 
  426.   mysql_close ( $this->db ); 
  427.  } 
  428. } 
  429. ?>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表