简单的PDO数据库操作类

<?php

	/**
	 * 
	 * @todo easy pdo db class
	 * @author ggbound
	 * 
	 *
	 */
	class BaseModel{
		
		private $_connect = null; //全局链接
		
		private $_PDOStatement = null; //全局pdoStatement
		
		private $_insertSql = null;
		
		private $_selectSql = null;
		
		/**
		 * @todo PDO link
		 * @since init Pdo Link
		 * @return $link
		 */
		public function __construct(){
			header("Content-type:text/html;charset=UTF-8");
			require_once '../configs/config.php';
			require_once "../functions/functions.php";
			$dbConfig = $config['db'];
			try {
				$dbOptions = array(
			        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ".$dbConfig['charset'],
			        PDO::ATTR_PERSISTENT => true
			    );
				$this->_connect = new PDO($dbConfig['dsn'], $dbConfig['username'], $dbConfig['password'] , $dbOptions);
			}catch (ErrorException $e){
				echo $e->message;
			}
			
		}
		
		/**
		 * @todo output sql errorinfo and write into logs
		 * @param $sql
		 * @param $result
		 * @return Array result Or String errorinfo
		 * @license write into logs function is not exist,add yourself.
		 */
		private function outputMysqlError($sql, $result){
			if ($result === false){
				$sqlErrorArray = $this->_connect -> errorInfo();
				return 'Error_Sql_String: '.$sql.' ; SQL_ERROR:'.$sqlErrorArray['2'].'!';
			}else{
				return $result;
			}
		}
		
		/**
		 * @todo Check Insert Values
		 * @param $data
		 * @return String:Format Sql String
		 * @example
		 * 		$data = array(
					'title' => '标题,啊啊',
					'content'=>'内容啊啊啊<script>alert(1);</script>'
				);
		 */
		private function FormatInsertSqlString($data){
			$formatString = ' (';
			$keys = array_keys($data);
			$keyFormatArr = array();
			foreach ($keys as $key){
				$keyFormatArr[] = '`'.$key.'`';
			}
			$vals = array_values($data);
			$valFormatArr = array();
			foreach ($vals as $val){
				$valFormatArr[] = '\''.htmlspecialchars(addslashes($val)).'\'';
			}
			$formatString .= join(',', $keyFormatArr);
			$formatString .= ') VALUES (';
			$formatString .= join(',', $valFormatArr);
			$formatString .= ') ';
			return $formatString;
		}
		
		/**
		 * @todo select 
		 * @param $tables
		 * @param $where
		 * @param $order
		 * @param $group
		 * @param $limit
		 * @return String errorinfo Or Array result
		 * @example 
		 * 	one 
		 * 		$sql = 'SELECT * FROM `artical` GROUP BY id,title';
		 * 		$result = $this->select($sql);
		 * 	two
		 * 		$sql = null;
				$tables = array('artical','artical');
				$where = array(
					'and' => array(array('title Like','标题')),
					'or'=>array(array('id=',33),array('id=',34))
				);
				$order = array('id DESC','title ASC');
				$group = array('title');
				$limit = '1,1';
				$result = $this->select($sql, $tables, $where, $group=null, $order, $limit);
		 */
		public function select($sql, $tables=null, $where = null, $group = null, $order = null, $limit = null){
			if (empty($sql)){
				$this->_selectSql = 'SELECT * FROM '
						.$this->tables($tables)
						.' '
						.$this->whereFormatString($where)
						.$this->group($group)
						.$this->order($order)
						.$this->limit($limit);
			}else{
				$this->_selectSql = $sql;
			}
			echo $this->_selectSql;
			$this->_PDOStatement = $this->_connect -> query($this->_selectSql);
			$result = $this->_PDOStatement -> fetchAll();
			return $this->outputMysqlError($sql , $result);
			$this->_connect -> closeCursor();
		}
		
		/**
		 * @todo tables
		 */
		private function tables($tables){
			$tableString = '';
			if (!empty($tables) && is_string($tables)){
				$tableString = $tableString;
			}else if(!empty($tables) && is_array($tables)){
				$tables = array_unique($tables);
				$tableString = join(',', $tables);
			}else{
				$tableString = '';
			}
			return $tableString;
		}
		
		/**
		 * @todo where
		 * @param $where
		 * @return String $whereString
		 * @example
		 * 		$where = array(
					'and' => array(array('title Like','标题')),
					'or'=>array(array('id=',33),array('id=',34))
				);
		 */
		private function whereFormatString($where){
			$whereString = '';
			if (!empty($where) && is_string($where)){
				$whereString = ' WHERE '.$where.' ';
			}else if (!empty($where) && is_array($where)){
				$whereAndStringArr = array();
				$whereOrStringArr = array();
				$whereAllArr = array();
				if(!empty($where['and'])){
					foreach ($where['and'] as $andkey => $andval){
						$andval[0] = trim($andval[0]);
						str_replace(strtolower('like'), '', strtolower($andval[0]),$count);
						if ($count < 1){
							$whereAndStringArr[] = $andval[0].'\''.$andval[1].'\''; 
						}else{
							$whereAndStringArr[] = $andval[0].' \'%'.$andval[1].'%\' '; 
						}
					}
				}
				if(!empty($where['or'])){
					foreach ($where['or'] as $key => $val){
						$val[0] = trim($val[0]);
						str_replace(strtolower('like'), '', strtolower($val[0]),$count);
						if ($count < 1){
							$whereOrStringArr[] = $val[0].'\''.$val[1].'\''; 
						}else{
							$whereOrStringArr[] = $val[0].' \'%'.$val[1].'%\' '; 
						}
					}
				}
				if(!empty($where)){
					foreach ($where as $key => $val){
						$val[0] = trim($val[0]);
						str_replace(strtolower('like'), '', strtolower($val[0]),$count);
						if ($count < 1){
							$whereAllArr[] = $val[0].'\''.$val[1].'\''; 
						}else{
							$whereAllArr[] = $val[0].' \'%'.$val[1].'%\' '; 
						}
					}
				}
				$whereAndString = join(' AND ', $whereAndStringArr);
				$whereOrString = join(' OR ', $whereOrStringArr);
				$whereAllString = join(' AND ', $whereAllArr);
				if (!empty($where['and']) && !empty($where['or'])){
					$whereString = ' WHERE '.$whereAndString.' AND ('.$whereOrString.') ';
				}else if(empty($where['and']) && !empty($where['or'])){
					$whereString = ' WHERE ('.$whereOrString.') ';
				}else if(!empty($where['and']) && empty($where['or'])){
					$whereString = ' WHERE '.$whereAndString.' ';
				}else{
					$whereString = ' WHERE '.$whereAllString.' ';
				}
			}else{
				$whereString = ' ';
			}
			return $whereString;
		}
		
		/**
		 * @todo order
		 * @example
		 * 	one $order = 'id DESC';
		 * 	two $order = array('id DESC','title ASC');
		 */
		private function order($order){
			$orderString = '';
			if (!empty($order) && is_string($order)){
				$orderString = ' ORDER BY '.$order.' ';
			}else if(!empty($order) && is_array($order)){
				$orderString = ' ORDER BY '.join(',', $order).' ';
			}else{
				$orderString = '';
			}
			return $orderString;
		}
		
		/**
		 * @todo group
		 * @example 
		 * 	one $group = 'title';
		 * 	two $group = array('id','title');
		 */
		private function group($group){
			$groupString = '';
			if (!empty($group) && is_string($group)){
				$groupString = ' GROUP BY '.$group.' ';
			}else if(!empty($group) && is_array($group)){
				$groupString = ' GROUP BY '.join(',', $group).' ';
			}else{
				$groupString = '';
			}
			return $groupString;
		}
		
		/**
		 * @todo limit
		 * @example
		 * 	one $limit = '1,1';
		 * 	two $limit = array(1,1);
		 */
		private function limit($limit){
			$limitString = '';
			if (!empty($limit) && is_string($limit)){
				$limitString = ' LIMIT '.$limit.' ';
			}else if(!empty($limit) && is_array($limit)){
				$limitString = ' LIMIT '.join(',', $limit).' ';
			}else{
				$limitString = '';
			}
			return $limitString;
		}
		
		/**
		 * @todo insert
		 * @param $table
		 * @param $params
		 * @return result boole true/false OR String errorinfo
		 * @example
		 *  $table = 'artical';
			$data = array(
				'title' => '标题,啊啊',
				'content'=>'内容啊啊啊<script>alert(1);</script>'
			);
			$result = $this->insert($table,$data);
		 */
		public function insert($table, $data){
			$this->_insertSql = $sql = 'INSERT INTO '.$table.$this->FormatInsertSqlString($data);
			$result = $this->_connect -> exec($sql);
			return $this->outputMysqlError($sql , $result);
			$this->_connect -> closeCursor();
		}
		
		/**
		 * @todo updateString
		 */
		private function formatUpdateString($data){
			$updateString = '';
			$formatArr = array();
			foreach ($data as  $key=>$val){
				$formatArr[] = '`'.$key.'` = \''.htmlspecialchars(addslashes($val)).'\'';
			}
			$updateString = join(',', $formatArr);
			return $updateString;
		}
		
		/**
		 * @todo update
		 * @param $table
		 * @param $data
		 * @param $where
		 * @return $result int rowNum
		 */
		public function Update($table, $data, $where){
			$sql = 'UPDATE `'.$table.'` SET '
				   .$this->formatUpdateString($data)
				   .$this->whereFormatString($where);
			$result = $this->_connect -> exec($sql);
			return $this->outputMysqlError($sql , $result);
			$this->_connect -> closeCursor();
		}
		
		/**
		 * @todo delete
		 * @param $table
		 * @param $where
		 * @return $result int rowNum
		 */
		public function Delete($table, $where){
			$sql = 'DELETE FROM `'.$table.'` '
				   .$this->whereFormatString($where);
			$result = $this->_connect -> exec($sql);
			return $this->outputMysqlError($sql , $result);
			$this->_connect -> closeCursor();
		}
		/**
		 * @todo count
		 * Enter description here ...
		 */
		public function Count(){
			$result = $this->_connect -> query($this->_selectSql) -> rowCount();
			return $result;
			$this->_connect -> closeCursor();
		}
		
		/**
		 * @todo getLastInsertId
		 * Enter description here ...
		 */
		public function getLastInsertId(){
			$result = (int) $this->_connect -> lastInsertId();
			return $result;
			$this->_connect -> closeCursor();
		}
		
	} 
	

该类只能满足简单的日常使用如遇到复杂的还请自行重新组装哟,仅供参考。

下面是个简单的示例:

<?php

	require_once 'BaseModel.php';
	
	class TestModel extends BaseModel {
		
		public function doTest(){
			//$sql = 'SELECT * FROM `artical` GROUP BY id,title';
			$tables = array('artical','artical');
			$params = array(
				'title' => '标题,啊啊',
				'content'=>'内容啊啊啊<script>alert(1);</script>'
			);
			/*$where = array(
				'and' => array(array('title Like','标题')),
				'or'=>array(array('id=',33),array('id=',34))
			);*/
			$order = array('id DESC','title ASC');
			$group = array('title');
			$limit = '1,1';
			$data = array('title'=>'标题'.time());
			$table = 'artical';
			$where = array(array('id=',33));
			//$result = $this->insert($table,$params);
			//$result = $this->select($sql=null, $tables, $where, $group=null, $order, $limit);
			$result = $this->Delete($table, $where);
			return $result;
		}
		
		public function getLastId(){
			$lastId = $this->getLastInsertId();
			return  $lastId;
		}
		
		public function countNum(){
			return $this->Count();
		}
		
	}
请慎重使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值