PHP PDO_MYSQL 鏈式操作 非鏈式操作類
阿新 • • 發佈:2018-12-30
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ // +----------------------------------------------------------------------+ // | PHP version 5 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2004 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 3.0 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available through the world-wide-web at the following url: | // | http://www.php.net/license/3_0.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // |[email protected] so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Authors: Original Author <[email protected]> | // | Your Name <[email protected]> | // +----------------------------------------------------------------------+ // // $Id:$class pdomysql { public $dbtype = 'mysql'; public $dbhost = '127.0.0.1'; public $dbport = '3306'; public $dbname = 'test'; public $dbuser = 'root'; public $dbpass = ''; public $charset = 'utf-8'; public $stmt = null; public $DB = null; public $connect= true; // 是否長連線 public $debug = true; private $parms = array(); private $sql = array( "db" => "", "from" => "", "where" => "", "order" => "", "limit" => "" ); /** * 建構函式 */ public function __construct() { $this->connect(); $this->DB->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); $this->DB->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); $this->execute('SET NAMES ' . $this->charset); } /** * 解構函式 */ public function __destruct() { $this->close(); } /** * *******************基本方法開始******************** */ /** * 作用:連結資料庫 */ public function connect() { try { $this->DB = new PDO($this->dbtype . ':host=' . $this->dbhost . ';port=' . $this->dbport . ';dbname=' . $this->dbname, $this->dbuser, $this->dbpass, array( PDO::ATTR_PERSISTENT => $this->connect )); } catch(PDOException $e) { die("Connect Error Infomation:" . $e->getMessage()); } } /** * 關閉資料連線 */ public function close() { $this->DB = null; } /** * 對字串進行轉義 */ public function quote($str) { return $this->DB->quote($str); } /** * 作用:獲取資料表裡的欄位 * 返回:表字段結構 * 型別:陣列 */ public function getFields($table) { $this->stmt = $this->DB->query("DESCRIBE $table"); $result = $this->stmt->fetchAll(PDO::FETCH_ASSOC); $this->stmt = null; return $result; } /** * 作用:獲得最後INSERT的主鍵ID * 返回:最後INSERT的主鍵ID * 型別:數字 */ public function getLastId() { return $this->DB->lastInsertId(); } /** * 作用:執行INSERT\UPDATE\DELETE * 返回:執行語句影響行數 * 型別:數字 */ public function execute($sql) { $this->getPDOError($sql); return $this->DB->exec($sql); } /** * 獲取要操作的資料 * 返回:合併後的SQL語句 * 型別:字串 */ private function getCode($table, $args) { $code = ''; if (is_array($args)) { foreach ($args as $k => $v) { if ($v == '') { continue; } $code.= "`$k`='$v',"; } } $code = substr($code, 0, -1); return $code; } public function optimizeTable($table) { $sql = "OPTIMIZE TABLE $table"; $this->execute($sql); } /** * 執行具體SQL操作 * 返回:執行結果 * 型別:陣列 */ private function _fetch($sql, $type) { $result = array(); $this->stmt = $this->DB->query($sql); $this->getPDOError($sql); $this->stmt->setFetchMode(PDO::FETCH_ASSOC); switch ($type) { case '0': $result = $this->stmt->fetch(); break; case '1': $result = $this->stmt->fetchAll(); break; case '2': $result = $this->stmt->rowCount(); break; } $this->stmt = null; return $result; } /** * *******************基本方法結束******************** */ /** * *******************Sql操作方法開始******************** */ /** * 作用:插入資料 * 返回:表內記錄 * 型別:陣列 * 引數:$db->insert('$table',array('title'=>'Zxsv')) */ public function add($table, $args) { $sql = "INSERT INTO `$table` SET "; $code = $this->getCode($table, $args); $sql.= $code; return $this->execute($sql); } /** * 修改資料 * 返回:記錄數 * 型別:數字 * 引數:$db->up($table,array('title'=>'Zxsv'),array('id'=>'1'),$where * ='id=3'); */ public function up($table, $args, $where) { $code = $this->getCode($table, $args); $sql = "UPDATE `$table` SET "; $sql.= $code; $sql.= " Where $where"; return $this->execute($sql); } /** * 作用:刪除資料 * 返回:表內記錄 * 型別:陣列 * 引數:$db->del($table,$condition = null,$where ='id=3') */ public function del($table, $where) { $sql = "DELETE FROM `$table` Where $where"; return $this->execute($sql); } /** * 作用:獲取單行資料 * 返回:表內第一條記錄 * 型別:陣列 * 引數:$db->fetOne($table,$condition = null,$field = '*',$where ='') */ public function fetOne($table, $field = '*', $where = false) { $sql = "SELECT {$field} FROM `{$table}`"; $sql.= ($where) ? " WHERE $where" : ''; return $this->_fetch($sql, $type = '0'); } /** * 作用:獲取所有資料 * 返回:表內記錄 * 型別:二維陣列 * 引數:$db->fetAll('$table',$condition = '',$field = '*',$orderby = '',$limit * = '',$where='') */ public function fetAll($table, $field = '*', $orderby = false, $where = false) { $sql = "SELECT {$field} FROM `{$table}`"; $sql.= ($where) ? " WHERE $where" : ''; $sql.= ($orderby) ? " ORDER BY $orderby" : ''; return $this->_fetch($sql, $type = '1'); } /** * 作用:獲取單行資料 * 返回:表內第一條記錄 * 型別:陣列 * 引數:select * from table where id='1' */ public function getOne($sql) { return $this->_fetch($sql, $type = '0'); } /** * 作用:獲取所有資料 * 返回:表內記錄 * 型別:二維陣列 * 引數:select * from table */ public function getAll($sql) { return $this->_fetch($sql, $type = '1'); } /** * 作用:獲取首行首列資料 * 返回:首行首列欄位值 * 型別:值 * 引數:select `a` from table where id='1' */ public function scalar($sql, $fieldname) { $row = $this->_fetch($sql, $type = '0'); return $row[$fieldname]; } /** * 獲取記錄總數 * 返回:記錄數 * 型別:數字 * 引數:$db->fetRow('$table',$condition = '',$where =''); */ public function fetRowCount($table, $field = '*', $where = false) { $sql = "SELECT COUNT({$field}) AS num FROM $table"; $sql.= ($where) ? " WHERE $where" : ''; return $this->_fetch($sql, $type = '0'); } /** * 獲取記錄總數 * 返回:記錄數 * 型別:數字 * 引數:select count(*) from table */ public function getRowCount($sql) { return $this->_fetch($sql, $type = '2'); } //鏈式操作開始 public function from($tableName) { $this->sql["from"] = "FROM " . $tableName; return $this; } public function db($tableName) { $this->sql["db"] = $tableName; return $this; } public function where($_where = '1=1') { $this->sql["where"] = "WHERE " . $_where; return $this; } public function order($_order = 'id DESC') { $this->sql["order"] = "ORDER BY " . $_order; return $this; } public function limit($_limitstart="30",$_limitend = '0') { if ($_limitend=="0"){ $this->sql["limit"] = "LIMIT 0," . $_limitstart; }else{ $this->sql["limit"] = "LIMIT $_limitstart," . $_limitend; } return $this; } /** * 獲取所有記錄 * 返回:所有記錄 * 型別:array * 引數: $pdomysql->from('dbname')->limit(30)->where('1=1')->select(); */ public function select($_select = '*') { //return "SELECT " . $_select . " " . (implode(" ", $this->sql)); $sql="SELECT " . $_select . " " . (implode(" ", $this->sql)); return $this->_fetch($sql, $type = '1'); } /** * 獲取一條記錄 * 返回:一條記錄 * 型別:array * 引數: $pdomysql->from('dbname')->limit(30)->where('1=1')->find(); */ public function find($_find = '*'){ $this->sql['limit']='limit 1'; $sql="SELECT " . $_find . " " . (implode(" ", $this->sql)); return $this->_fetch($sql, $type = '0'); } /** * 插入一條資料 * 返回:執行結果 * 型別:bool * 引數: $pdomysql->db('dbname')->insert(array('col1'="sadsd")); */ public function insert($_insert=array()){ $table=$this->sql['db']; $sql = "INSERT INTO `$table` SET "; $code = $this->getCode($table, $args); $sql.= $code; return $this->execute($sql); } /** * 刪除 * 返回:刪除結果 * 型別:bool * 引數: $pdomysql->from('dbname')->where('1=1')->delete(); */ public function delete(){ $sql="DELETE " . (implode(" ", $this->sql)); return $this->execute($sql); } public function update(){ } //鏈式操作end /** * *******************Sql操作方法結束******************** */ /** * *******************錯誤處理開始******************** */ /** * 設定是否為除錯模式 */ public function setDebugMode($mode = true) { return ($mode == true) ? $this->debug = true : $this->debug = false; } /** * 捕獲PDO錯誤資訊 * 返回:出錯資訊 * 型別:字串 */ private function getPDOError($sql) { $this->debug ? $this->errorfile($sql) : ''; if ($this->DB->errorCode() != '00000') { $info = ($this->stmt) ? $this->stmt->errorInfo() : $this->DB->errorInfo(); echo ($this->sqlError('mySQL Query Error', $info[2], $sql)); exit(); } } private function getSTMTError($sql) { $this->debug ? $this->errorfile($sql) : ''; if ($this->stmt->errorCode() != '00000') { $info = ($this->stmt) ? $this->stmt->errorInfo() : $this->DB->errorInfo(); echo ($this->sqlError('mySQL Query Error', $info[2], $sql)); exit(); } } /** * 寫入錯誤日誌 */ private function errorfile($sql) { echo $sql . '<br />'; $errorfile = __DIR__ . '/dberrorlog.php'; $sql = str_replace(array( "\n", "\r", "\t", " ", " ", " " ) , array( " ", " ", " ", " ", " ", " " ) , $sql); if (!file_exists($errorfile)) { $fp = file_put_contents($errorfile, "<?PHP exit('Access Denied'); ?>\n" . $sql); } else { $fp = file_put_contents($errorfile, "\n" . $sql, FILE_APPEND); } } /** * 作用:執行錯誤資訊 * 返回:執行錯誤資訊和SQL語句 * 型別:字元 */ private function sqlError($message = '', $info = '', $sql = '') { $html = ''; if ($message) { $html.= $message; } if ($info) { $html.= 'SQLID: ' . $info; } if ($sql) { $html.= 'ErrorSQL: ' . $sql; } throw new Exception($html); } /** * *******************錯誤處理結束******************** */ }