백엔드 개발 PHP 튜토리얼 php实现mysql数据库备份类_php实例

php实现mysql数据库备份类_php实例

Jun 07, 2016 pm 05:26 PM
mysql php

1、实例化DbBak需要告诉它两件事:数据服务器在哪里($connectid)、备份到哪个目录($backupDir): 

require_once('DbBak.php');    
require_once('TableBak.php');    
$connectid = mysql_connect('localhost','root','123456');    
$backupDir = 'data';    
$DbBak = new DbBak($connectid,$backupDir);    

2、然后就可以开始备份数据库了,你不仅能够指定备份那个数据库,而且能详细设置只备份那几个表:
   2.1如果你想备份mybbs库中的所有表,只要这样: 

$DbBak->backupDb('mybbs');    

2.2如果你只想备份mybbs库中的board、face、friendlist表,可以用一个一维数组指定:

$DbBak->backupDb('mybbs',array('board','face','friendsite'));    

2.3如果只想备份一个表,比如board表:
$DbBak->backupDb('mybbs','board');    
3,数据恢复:
对于2.1、2.1、2.3三种情况,只要相应的修改下语句,把backupDb换成restoreDb就能实现数据恢复了:

$DbBak->restoreDb('mybbs');   
SQL代码
$DbBak->restoreDb('mybbs',array('board','face','friendsite'));   
PHP代码
$DbBak->restoreDb('mybbs','board');   
PHP代码
require_once('TableBak.php');    
class DbBak {    
var $_mysql_link_id;    
var $_dataDir;    
var $_tableList;    
var $_TableBak;    

function DbBak($_mysql_link_id,$dataDir)    
{    
( (!is_string($dataDir)) || strlen($dataDir)==0) && die('error:$datadir is not a string');    
!is_dir($dataDir) && mkdir($dataDir);    
$this->_dataDir = $dataDir;    
$this->_mysql_link_id = $_mysql_link_id;    
}    

function backupDb($dbName,$tableName=null)    
{    
( (!is_string($dbName)) || strlen($dbName)==0 ) && die('$dbName must be a string value');    
//step1:选择数据库:    
mysql_select_db($dbName);    
//step2:创建数据库备份目录    
$dbDir = $this->_dataDir.DIRECTORY_SEPARATOR.$dbName;    
!is_dir($dbDir) && mkdir($dbDir);    
//step3:得到数据库所有表名 并开始备份表    
$this->_TableBak = new TableBak($this->_mysql_link_id,$dbDir);    
if(is_null($tableName)){//backup all table in the db    
$this->_backupAllTable($dbName);    
return;    
}    
if(is_string($tableName)){    
(strlen($tableName)==0) && die('....');    
$this->_backupOneTable($dbName,$tableName);    
return;    
}    
if (is_array($tableName)){    
foreach ($tableName as $table){    
( (!is_string($table)) || strlen($table)==0 ) && die('....');    
}    
$this->_backupSomeTalbe($dbName,$tableName);    
return;    
}    
}    

function restoreDb($dbName,$tableName=null){    
( (!is_string($dbName)) || strlen($dbName)==0 ) && die('$dbName must be a string value');    
//step1:检查是否存在数据库 并连接:    
@mysql_select_db($dbName) || die("the database $dbName dose not exists");    
//step2:检查是否存在数据库备份目录    
$dbDir = $this->_dataDir.DIRECTORY_SEPARATOR.$dbName;    
!is_dir($dbDir) && die("$dbDir not exists");    
//step3:start restore    
$this->_TableBak = new TableBak($this->_mysql_link_id,$dbDir);    
if(is_null($tableName)){//backup all table in the db    
$this->_restoreAllTable($dbName);    
return;    
}    
if(is_string($tableName)){    
(strlen($tableName)==0) && die('....');    
$this->_restoreOneTable($dbName,$tableName);    
return;    
}    
if (is_array($tableName)){    
foreach ($tableName as $table){    
( (!is_string($table)) || strlen($table)==0 ) && die('....');    
}    
$this->_restoreSomeTalbe($dbName,$tableName);    
return;    
}    
}    

function _getTableList($dbName)    
{    
$tableList = array();    
$result=mysql_list_tables($dbName,$this->_mysql_link_id);    
for ($i = 0; $i         array_push($tableList,mysql_tablename($result, $i));    
}    
mysql_free_result($result);    
return $tableList;    
}    

function _backupAllTable($dbName)    
{    
foreach ($this->_getTableList($dbName) as $tableName){    
$this->_TableBak->backupTable($tableName);    
}    
}    

function _backupOneTable($dbName,$tableName)    
{    
!in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名$tableName在数据库中不存在");    
$this->_TableBak->backupTable($tableName);    
}    

function _backupSomeTalbe($dbName,$TableNameList)    
{    
foreach ($TableNameList as $tableName){    
!in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名$tableName在数据库中不存在");    
}    
foreach ($TableNameList as $tableName){    
$this->_TableBak->backupTable($tableName);    
}    
}    

function _restoreAllTable($dbName)    
{    
//step1:检查是否存在所有数据表的备份文件 以及是否可写:    
foreach ($this->_getTableList($dbName) as $tableName){    
$tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR    
            . $dbName.DIRECTORY_SEPARATOR    
               . $tableName.DIRECTORY_SEPARATOR    
            . $tableName.'.sql';    
!is_writeable ($tableBakFile) && die("$tableBakFile not exists or unwirteable");    
}    
//step2:start restore    
foreach ($this->_getTableList($dbName) as $tableName){    
$tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR    
               . $dbName.DIRECTORY_SEPARATOR    
               . $tableName.DIRECTORY_SEPARATOR    
               . $tableName.'.sql';    
$this->_TableBak->restoreTable($tableName,$tableBakFile);    
}    
}    

function _restoreOneTable($dbName,$tableName)    
{    
//step1:检查是否存在数据表:    
!in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名$tableName在数据库中不存在");    
//step2:检查是否存在数据表备份文件 以及是否可写:    
$tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR    
         . $dbName.DIRECTORY_SEPARATOR    
      . $tableName.DIRECTORY_SEPARATOR    
         . $tableName.'.sql';    
!is_writeable ($tableBakFile) && die("$tableBakFile not exists or unwirteable");    
//step3:start restore    
$this->_TableBak->restoreTable($tableName,$tableBakFile);    
}    
function _restoreSomeTalbe($dbName,$TableNameList)    
{    
//step1:检查是否存在数据表:    
foreach ($TableNameList as $tableName){    
!in_array($tableName,$this->_getTableList($dbName)) && die("指定的表名$tableName在数据库中不存在");    
}    
//step2:检查是否存在数据表备份文件 以及是否可写:    
foreach ($TableNameList as $tableName){    
$tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR    
               . $dbName.DIRECTORY_SEPARATOR    
               . $tableName.DIRECTORY_SEPARATOR    
               . $tableName.'.sql';    
!is_writeable ($tableBakFile) && die("$tableBakFile not exists or unwirteable");    
}    
//step3:start restore:    
foreach ($TableNameList as $tableName){    
$tableBakFile = $this->_dataDir.DIRECTORY_SEPARATOR    
               . $dbName.DIRECTORY_SEPARATOR    
               . $tableName.DIRECTORY_SEPARATOR    
               . $tableName.'.sql';    
$this->_TableBak->restoreTable($tableName,$tableBakFile);    
}    
}    
}    
?>     

复制代码 代码如下:

//只有DbBak才能调用这个类     
class TableBak{     
var $_mysql_link_id;     
var $_dbDir;     
//private $_DbManager;     
function TableBak($mysql_link_id,$dbDir)     
{     
$this->_mysql_link_id = $mysql_link_id;     
$this->_dbDir = $dbDir;     
}     

function backupTable($tableName)     
{     
//step1:创建表的备份目录名:     
$tableDir = $this->_dbDir.DIRECTORY_SEPARATOR.$tableName;     
!is_dir($tableDir) && mkdir($tableDir);     
//step2:开始备份:     
$this->_backupTable($tableName,$tableDir);     
}     

function restoreTable($tableName,$tableBakFile)     
{     
set_time_limit(0);     
$fileArray = @file($tableBakFile) or die("can open file $tableBakFile");     
$num = count($fileArray);     
mysql_unbuffered_query("DELETE FROM $tableName");     
$sql = $fileArray[0];     
for ($i=1;$imysql_unbuffered_query($sql.$fileArray[$i]) or (die (mysql_error()));     
}     
return true;     
}     

function _getFieldInfo($tableName){     
$fieldInfo = array();     
$sql="SELECT * FROM $tableName LIMIT 1";     
$result = mysql_query($sql,$this->_mysql_link_id);     
$num_field=mysql_num_fields($result);     
for($i=0;$i$field_name=mysql_field_name($result,$i);     
$field_type=mysql_field_type($result,$i);     
$fieldInfo[$field_name] = $field_type;     
}     
mysql_free_result($result);     
return $fieldInfo;     
}     
function _quoteRow($fieldInfo,$row){     
foreach ($row as $field_name=>$field_value){     
$field_value=strval($field_value);     
switch($fieldInfo[$field_name]){       
case "blob":     $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;         
case "string": $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;       
case "date":     $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;       
case "datetime": $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;       
case "time":     $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;       
case "unknown":   $row[$field_name] = "'".mysql_escape_string($field_value)."'";break;         
case "int":     $row[$field_name] = intval($field_value); break;     
case "real":     $row[$field_name] = intval($field_value); break;     
case "timestamp":$row[$field_name] = intval($field_value); break;     
default:     $row[$field_name] = intval($field_value); break;     
}     
}     
return $row;     
}     
function _backupTable($tableName,$tableDir)     
{     
//取得表的字段类型:     
$fieldInfo = $this->_getFieldInfo($tableName);     

//step1:构造INSERT语句前半部分 并写入文件:     
$fields = array_keys($fieldInfo);     
$fields = implode(',',$fields);     
$sqltext="INSERT INTO $tableName($fields)VALUES \r\n";     
$datafile = $tableDir.DIRECTORY_SEPARATOR.$tableName.'.sql';     
(!$handle = fopen($datafile,'w')) && die("can not open file $datafile");     
(!fwrite($handle, $sqltext))   && die("can not write data to file $datafile");     
fclose($handle);     

//step2:取得数据 并写入文件:     
//取出表资源:     
set_time_limit(0);     
$sql = "select * from $tableName";     
$result = mysql_query($sql,$this->_mysql_link_id);     
//打开数据备份文件:$tableName.xml     
$datafile = $tableDir.DIRECTORY_SEPARATOR.$tableName.'.sql';     
(!$handle = fopen($datafile,'a')) && die("can not open file $datafile");     
//逐条取得表记录并写入文件:     
while ($row = mysql_fetch_assoc($result)) {     
$row = $this->_quoteRow($fieldInfo,$row);      
$record='(' . implode(',',$row) . ");\r\n";     
(!fwrite($handle, $record))   && die("can not write data to file $datafile");     
}     
mysql_free_result($result);     
//关闭文件:     
fclose($handle);     

return true;     
}     

}     
?>   
 

备份mybbs数据库:

SQL代码
//example 1 backup:    
require_once('DbBak.php');    
require_once('TableBak.php');    
$connectid = mysql_connect('localhost','root','123456');    
$backupDir = 'data';    
$DbBak = new DbBak($connectid,$backupDir);    
$DbBak->backupDb('mybbs');    

恢复mybbs数据库: 

复制代码 代码如下:

require_once('DbBak.php');     
require_once('TableBak.php');     
$connectid = mysql_connect('localhost','root','123456');     
$backupDir = 'data';     
$DbBak = new DbBak($connectid,$backupDir);     
$DbBak->restoreDb('mybbs'); 
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법 Dec 20, 2024 am 11:31 AM

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 Dec 09, 2024 am 11:42 AM

MySQL 8.4(2024년 최신 LTS 릴리스)에 도입된 주요 변경 사항 중 하나는 "MySQL 기본 비밀번호" 플러그인이 더 이상 기본적으로 활성화되지 않는다는 것입니다. 또한 MySQL 9.0에서는 이 플러그인을 완전히 제거합니다. 이 변경 사항은 PHP 및 기타 앱에 영향을 미칩니다.

PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? PHP에서 HTML/XML을 어떻게 구문 분석하고 처리합니까? Feb 07, 2025 am 11:57 AM

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열로 모음을 계산하는 PHP 프로그램 문자열로 모음을 계산하는 PHP 프로그램 Feb 07, 2025 pm 12:12 PM

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

이전에 몰랐던 후회되는 PHP 함수 7가지 이전에 몰랐던 후회되는 PHP 함수 7가지 Nov 13, 2024 am 09:42 AM

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

PHP가 MySQL에 연결된 후 페이지가 비어 있습니다. 유효하지 않은 다이 () 함수의 이유는 무엇입니까? PHP가 MySQL에 연결된 후 페이지가 비어 있습니다. 유효하지 않은 다이 () 함수의 이유는 무엇입니까? Apr 01, 2025 pm 03:03 PM

PHP가 MySQL에 연결 한 후 페이지가 비어 있고 Die () 함수가 실패한 이유가 있습니다. PHP와 MySQL 데이터베이스 간의 연결을 배울 때는 종종 혼란스러운 것들이 발생합니다 ...

2024년 개발자를 위한 상위 10대 PHP CMS 플랫폼 2024년 개발자를 위한 상위 10대 PHP CMS 플랫폼 Dec 05, 2024 am 10:29 AM

CMS는 콘텐츠 관리 시스템을 의미합니다. 사용자가 고급 기술 지식 없이도 디지털 콘텐츠를 생성, 관리 및 수정할 수 있는 소프트웨어 애플리케이션 또는 플랫폼입니다. CMS를 사용하면 사용자가 콘텐츠를 쉽게 생성하고 구성할 수 있습니다.

See all articles