复制代码 代码如下:
/**
* 数据库备份还原类
* @author xialeistudio
* Class DatabaseTool
*/
class DatabaseTool
{
private $handler;
private $config = array(
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => '',
'database' => 'test',
'charset' => 'utf-8',
'target' => 'sql.sql'
);
private $tables = array();
private $error;
private $begin; //开始时间
/**
* 架构方法
* @param array $config
*/
public function __construct($config = array())
{
$this->begin = microtime(true);
$config = is_array($config) ? $config : array();
$this->config = array_merge($this->config, $config);
//启动PDO连接
if (!$this->handler instanceof PDO)
{
try
{
$this->handler = new PDO("mysql:host={$this->config['host']}:{$this->config['port']};dbname={$this->config['database']}", $this->config['user'], $this->config['password']);
}
catch (PDOException $e)
{
$this->error = $e->getMessage();
return false;
}
catch (Exception $e)
{
$this->error = $e->getMessage();
return false;
}
}
}
/**
* 备份
* @param array $tables
* @return bool
*/
public function backup($tables = array())
{
//存储表定义语句的数组
$ddl = array();
//存储数据的数组
$data = array();
$this->setTables($tables);
if (!empty($this->tables))
{
foreach ($this->tables as $table)
{
$ddl[] = $this->getDDL($table);
$data[] = $this->getData($table);
}
//开始写入
$this->writeToFile($this->tables, $ddl, $data);
}
else
{
$this->error = '数据库中没有表!';
return false;
}
}
/**
* 设置要备份的表
* @param array $tables
*/
private function setTables($tables = array())
{
if (!empty($tables) && is_array($tables))
{
//备份指定表
$this->tables = $tables;
}
else
{
//备份全部表
$this->tables = $this->getTables();
}
}
/**
* 查询
* @param string $sql
* @return mixed
*/
private function query($sql = '')
{
$stmt = $this->handler->query($sql);
$stmt->setFetchMode(PDO::FETCH_NUM);
$list = $stmt->fetchAll();
return $list;
}
/**
* 获取全部表
* @return array
*/
private function getTables()
{
$sql = 'SHOW TABLES';
$list = $this->query($sql);
$tables = array();
foreach ($list as $value)
{
$tables[] = $value[0];
}
return $tables;
}
/**
* 获取表定义语句
* @param string $table
* @return mixed
*/
private function getDDL($table = '')
{
$sql = "SHOW CREATE TABLE `{$table}`";
$ddl = $this->query($sql)[0][1] . ';';
return $ddl;
}
/**
* 获取表数据
* @param string $table
* @return mixed
*/
private function getData($table = '')
{
$sql = "SHOW COLUMNS FROM `{$table}`";
$list = $this->query($sql);
//字段
$columns = '';
//需要返回的SQL
$query = '';
foreach ($list as $value)
{
$columns .= "`{$value[0]}`,";
}
$columns = substr($columns, 0, -1);
$data = $this->query("SELECT * FROM `{$table}`");
foreach ($data as $value)
{
$dataSql = '';
foreach ($value as $v)
{
$dataSql .= "'{$v}',";
}
$dataSql = substr($dataSql, 0, -1);
$query .= "INSERT INTO `{$table}` ({$columns}) VALUES ({$dataSql});\r\n";
}
return $query;
}
/**
* 写入文件
* @param array $tables
* @param array $ddl
* @param array $data
*/
private function writeToFile($tables = array(), $ddl = array(), $data = array())
{
$str = "/*\r\nMySQL Database Backup Tools\r\n";
$str .= "Server:{$this->config['host']}:{$this->config['port']}\r\n";
$str .= "Database:{$this->config['database']}\r\n";
$str .= "Data:" . date('Y-m-d H:i:s', time()) . "\r\n*/\r\n";
$str .= "SET FOREIGN_KEY_CHECKS=0;\r\n";
$i = 0;
foreach ($tables as $table)
{
$str .= "-- ----------------------------\r\n";
$str .= "-- Table structure for {$table}\r\n";
$str .= "-- ----------------------------\r\n";
$str .= "DROP TABLE IF EXISTS `{$table}`;\r\n";
$str .= $ddl[$i] . "\r\n";
$str .= "-- ----------------------------\r\n";
$str .= "-- Records of {$table}\r\n";
$str .= "-- ----------------------------\r\n";
$str .= $data[$i] . "\r\n";
$i++;
}
echo file_put_contents($this->config['target'], $str) ? '备份成功!花费时间' . (microtime(true) - $this->begin) . 'ms' : '备份失败!';
}
/**
* 错误信息
* @return mixed
*/
public function getError()
{
return $this->error;
}
public function restore($path = '')
{
if (!file_exists($path))
{
$this->error('SQL文件不存在!');
return false;
}
else
{
$sql = $this->parseSQL($path);
try
{
$this->handler->exec($sql);
echo '还原成功!花费时间', (microtime(true) - $this->begin) . 'ms';
}
catch (PDOException $e)
{
$this->error = $e->getMessage();
return false;
}
}
}
/**
* 解析SQL文件为SQL语句数组
* @param string $path
* @return array|mixed|string
*/
private function parseSQL($path = '')
{
$sql = file_get_contents($path);
$sql = explode("\r\n", $sql);
//先消除--注释
$sql = array_filter($sql, function ($data)
{
if (empty($data) || preg_match('/^--.*/', $data))
{
return false;
}
else
{
return true;
}
});
$sql = implode('', $sql);
//删除/**/注释
$sql = preg_replace('/\/\*.*\*\//', '', $sql);
return $sql;
}
}

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。


핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

뜨거운 주제



