demo
<?php
/**
* 讀取 sql 文件並寫入數據庫
* @version
*/
class DBManager
{
var $dbHost =
var $dbUser =
var $dbPassword =
var $dbSchema =
function __construct($host
{
$this
$this
$this
$this
}
function createFromFile($sqlPath
{
//判斷文件是否存在
if(!file_exists($sqlPath))
return false;
$handle = fopen($sqlPath
$sqlStr = fread($handle
//通過sql語法的語句分割符進行分割
$segment = explode(";"
//var_dump($segment);
//去掉注釋和多余的空行
foreach($segment as & $statement)
{
$sentence = explode("/n"
$newStatement = array();
foreach($sentence as $subSentence)
{
if(
{
//判斷是會否是注釋
$isComment = false;
foreach($commenter as $comer)
{
if(eregi("^("
{
$isComment = true;
break;
}
}
//如果不是注釋
if(!$isComment)
$newStatement[] = $subSentence;
}
}
$statement = $newStatement;
}
//對表名加前綴
if(
{
//只有表名在第一行出現時才有效 例如 CREATE TABLE talbeName
$regxTable = "^[/`/
$regxLeftWall = "^[/`/
$sqlFlagTree = array(
"CREATE" => array(
"TABLE" => array(
"$regxTable" =>
)
)
"INSERT" => array(
"INTO" => array(
"$regxTable" =>
)
)
);
foreach($segment as & $statement)
{
$tokens = split(" "
$tableName = array();
$this
if(empty($tableName[
{
$newTableName = $prefix
}
else{
$newTableName = $tableName[
}
$statement[
}
}
//組合sql語句
foreach($segment as & $statement)
{
$newStmt =
foreach($statement as $sentence)
{
$newStmt = $newStmt
}
$statement = $newStmt;
}
//用於測試
//var_dump($segment);
//writeArrayToFile(
//
self::saveByQuery($segment);
return true;
}
private function saveByQuery($sqlArray)
{
$conn = mysql_connect($this
mysql_select_db($this
foreach($sqlArray as $sql)
{
mysql_query($sql);
}
mysql_close($conn);
}
private function findTableName($sqlFlagTree
{
$regxLeftWall = "^[/`/
if(count($tokens)<=$tokensKey)
return false;
if(
{
return self::findTableName($sqlFlagTree
}
else
{
foreach($sqlFlagTree as $flag => $v)
{
if(eregi($flag
{
if(
{
$tableName[
if(eregi($regxLeftWall
{
$tableName[
}
return true;
}
else{
return self::findTableName($v
}
}
}
}
return false;
}
}
function writeArrayToFile($fileName
{
$handle=fopen($fileName
$text =
foreach($dataArray as $data)
{
$text = $text
}
fwrite($handle
}
//測試
$dbM = new DBManager(
$dbM
?>
data
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
CREATE TABLE `allowed` (
`bhash` blob NOT NULL
`bname` varchar(
PRIMARY KEY (`bhash`(
) ENGINE=MyISAM DEFAULT CHARSET=gb
CREATE TABLE `allowed_ex` (
`bhash` blob NOT NULL
`badded` datetime NOT NULL
`bsize` bigint(
`bfiles` int(
PRIMARY KEY (`bhash`(
) ENGINE=MyISAM DEFAULT CHARSET=gb
CREATE TABLE `category` (
`cid` int(
`name` varchar(
`sequence` int(
PRIMARY KEY (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf
INSERT INTO `category` (`cid`
(
(
(
注:對於phpmyadmin 生成的sql文件均適用
From:http://tw.wingwit.com/Article/program/PHP/201311/21281.html