php备份数据库类分享

yipeiwu_com5年前PHP代码库

php备份数据库类分享

<?php
  /**
  *  
  *  @name php备份数据库 
  *  @param string  $DbHost    连接主机
  *  @param string  $DbUser    用户名
  *  @param string  $DbPwd    连接密码
  *  @param string  $DbName    要备份的数据库
  *  @param string  $saveFileName 要保存的文件名, 默认文件保存在当前文件夹中,以日期作区分
  *  @return Null
  *  @example backupMySqlData('localhost', 'root', '123456', 'YourDbName');
  *
  */
  function backupMySqlData($DbHost, $DbUser, $DbPwd, $DbName, $saveFileName = '')
  {
    header("Content-type:text/html;charset=utf-8");
    error_reporting(0);
    set_time_limit(0);

    echo '数据备份中,请稍候......<br />';

    $link = mysql_connect($DbHost, $DbUser, $DbPwd) or die('数据库连接失败: ' . mysql_error());
    mysql_select_db($DbName) or die('数据库连接失败: ' . mysql_error());
    mysql_query('set names utf8');
    
    // 声明变量
    $isDropInfo   = '';
    $insertSQL   = '';
    $row      = array();
    $tables     = array();
    $tableStructure = array();
    $fileName    = ($saveFileName ? $saveFileName : 'MySQL_data_bakeup_') . date('YmdHis') . '.sql';

    // 枚举该数据库所有的表
    $res = mysql_query("SHOW TABLES FROM $DbName");
    while ($row = mysql_fetch_row($res)) {

      $tables[] = $row[0];

    }
    mysql_free_result($res);

    // 枚举所有表的创建语句
    foreach ($tables as $val) {

      $res = mysql_query("show create table $val", $link);
      $row = mysql_fetch_row($res);

      $isDropInfo   = "DROP TABLE IF EXISTS `" . $val . "`;\r\n";
      $tableStructure = $isDropInfo . $row[1] . ";\r\n";

      file_put_contents($fileName, $tableStructure, FILE_APPEND);
      mysql_free_result($res);
    }

    // 枚举所有表的INSERT语句
    foreach ($tables as $val) {

      $res = mysql_query("select * from $val");

      // 没有数据的表不执行insert
      while ($row = mysql_fetch_row($res)) {

        $sqlStr = "INSERT INTO `".$val."` VALUES (";

        foreach($row as $v){

          $sqlStr .= "'$v',";

        }
        //去掉最后一个逗号
        $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 1);
        $sqlStr .= ");\r\n";

        file_put_contents($fileName, $sqlStr, FILE_APPEND);
      }
      mysql_free_result($res);
    }

    echo '数据备份成功!';
  }
   // 调用此方法 
  backupMySqlData('localhost', 'root', '123456', 'YouDbName');  
?>

以上所述就是本文的全部内容了,希望大家能够喜欢。

相关文章

php 判断字符串中是否包含html标签

function judgeHtml($str){ if($str != strip_tags($str)){  echo '有'; }else{...

php查看session内容的函数

如:name|s:4:"tasm";passwd|s:6:"111111";mode|s:1:"1",也知道该session存放的位置,而且可以上传文件,所以嘛,当时就做了一次小小的黑客...

PHP得到mssql的存储过程的输出参数功能实现

在开发过程中可能会遇到无法取得MSSQL存储过程的输出参数,很多朋友都不知道该怎么办,本文将详细介绍PHP得到mssql的存储过程的输出参数功能实现,需要了解的朋友可以参考下复制代码 代...

PHP stream_context_create()作用和用法分析

作用:创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。 函数原型:res...

PHP实现将多个文件中的内容合并为新文件的方法示例

本文实例讲述了PHP实现将多个文件中的内容合并为新文件的方法。分享给大家供大家参考,具体如下: function test() { $hostdir= iconv("utf-8"...