sql php
1.打開sql文件,放入一個變量(字符串類型)當中
2.使用正則替換掉當中的注釋(“--”與“/**/”)
3.使用explode分割成為一個數組並去除每行的空格
4.鏈接數據庫之後使用my_query()執行sql
// +------------------------------------------------------------------------------------------// | Author: longDD// +------------------------------------------------------------------------------------------// | There is no true,no evil,no light,there is only power.// +------------------------------------------------------------------------------------------// | Description: import sql Dates: 2014-08-07// +------------------------------------------------------------------------------------------class ImportSql{/** @var $content 數據庫連接 */protected $connect = null;/** @var $db 數據庫對象 */protected $db = null;/** @var $sqlFile sql文件 */public $sqlFile = "";/** @array @sqlArr sql語句數組 */public $sqlArr = array();/*** 構造函數** @param string $host 主機地址* @param string $user 用戶名* @param string $pw 密碼* @param $db_name 數據庫名稱* @return void*/public function __construct($host, $user, $pw, $db_name){/** 連接數據庫 */$this->connect = mysql_connect($host, $user, $pw) or die("Could not connect: " . mysql_error());/** 選中數據庫 */$this->db = mysql_select_db($db_name, $this->connect) or die("Yon can not select the table:" . mysql_error());}/*** 導入sql文件** @param string $url 文件路徑* @return true 導入成返回true*/public function Import($url){if(!file_exists($url)){exit("文件不存在!");}$this->sqlFile = file_get_contents($url);if (!$this->sqlFile){exit("打開文件錯誤!");}else{$this->GetSqlArr();if ($this->Runsql()){return true;}}}/*** 獲取sql語句數組** @return void*/public function GetSqlArr(){/** 去除注釋 */$str = $this->sqlFile;$str = preg_replace('/--.*/i', '', $str);$str = preg_replace('/\/\*.*\*\/(\;)?/i', '', $str);/** 去除空格 創建數組 */$str = explode(";\n", $str);foreach ($str as $v){$v = trim($v);if (empty($v)){continue;}else{$this->sqlArr[] = $v;}}}/*** 執行sql文件** @return true 執行成功返回true*/public function RunSql(){/** 開啟事務 */if (mysql_query('BEGIN')){foreach ($this->sqlArr as $k => $v){if (!mysql_query($v)){/** 回滾 */mysql_query('ROLLBACK');exit("sql語句錯誤:第" . $k . "行" . mysql_error());}}/** 提交事務 */mysql_query('COMMIT');return true;}else{exit('無法開啟事務!');}}}// +------------------------------------------------------------------------------------------// | End of ImportSql class// +------------------------------------------------------------------------------------------/*** This is a example.*/header("Content-type:text/html;charset=utf-8");$sql = new ReadSql("localhost", "root", "", "log_db");$rst = $sql->Import("./log_db.sql");if ($rst){echo "Success!";}// +------------------------------------------------------------------------------------------// | End of file ImportSql.php// +------------------------------------------------------------------------------------------// | Location: ./ImportSql.php// +------------------------------------------------------------------------------------------