Heim  >  Artikel  >  php教程  >  Mysql PDO基础操作

Mysql PDO基础操作

PHP中文网
PHP中文网Original
2016-05-23 17:10:061170Durchsuche


tableKey = $tableKey;
	}
	/**
	 * 获取库文件信息
	 * 
	*/
	public function getConfig()
	{
		if( ! isset($this->tableKey) )
		{
			throw new QException('当前操作表不存在');
		}
		$dbconfig = $this->DbConfig();
		require($dbconfig);
		$this->configFile = $tbl[$this->tableKey];
		if( !isset( $this->configFile )) 
		{
			throw new QException('当前操作表配置不存在'.$this->tableKey);
		}
	}
	
	/**
	 * 数据库链接
	 * 
	 */
	public function init()
	{
		$this->getConfig();
		if( ! file_exists($this->configFile['configFile']) )
		{
			throw new QException('当前链接配置不存在'.$this->configFile['configFile']);
		}
		require $this->configFile['configFile'];
		try {
			$this->pdo =  new PDO(
				$dsn,
				$user,
				$password, 
				array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ".$encode,PDO::FETCH_ASSOC=>true));
		    //$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); //php预处理错误
		} catch (Exception $e) {
			
			exit('数据库连接失败,错误信息:'. $e->getMessage());
		}
	}
	
	/**
	 * 表组合
	 * 
	 */
	private function tablePrefix()
	{
		$this->getConfig();
		return $this->configFile['tablePrefix'].$this->tableKey;
	}
	
	/**
	 * sql执行
	 * 
	 * @param string $sql
	 */
	private function query( $sql ) 
	{
		$this->init();
		return $this->pdo->query($sql);
	}
	
	/**
	 * 反回执行受影响行数
	 * 
	 * 适合于 插入 、修改
	 * @param string $sql
	 */
	private function exec( $sql )
	{
		$this->init();
		return $this->pdo->exec($sql);
	}
	
	/**
	 * 获取一条数据
	 *
	 * @access	public
	 * @param	string	$tableKey	数据表标识
	 * @param	array	$rule		数据查询规则
	 * @return	array
	 */
	public function findOne( $param )
	{
		$param  = $this->combined( $param );
		$where = !empty($param['where']) ? ' WHERE '.$param['where'] :  ' '.$param['limit'] ;
		$sql    = 'SELECT '.$param['col'].' FROM `'.$this->tablePrefix().'`'.$where.' LIMIT 1';
		return $this->query($sql)->fetch();
	}

	/**
	 * 获取多条数据
	 *
	 * @access	public
	 * @param	string	$tableKey	数据表标识
	 * @param	array	$rule		数据查询规则
	 * @return	array
	 */
	public function find( $param )
	{
		$param = $this->combined( $param );

		$where = !empty($param['in']) ? ' WHERE '.$param['in'] :  ' '.$param['limit'] ;
		$sql   = 'SELECT '.$param['col'].' FROM `'.$this->tablePrefix().'`'.$where;
		
		return $this->query($sql)->fetchAll();
	}
	
	/**
	 * 获取多条数据(数据分页时用)
	 *
	 * @access	public
	 * @param	string	$tableKey	数据表标识
	 * @param	array	$rule		数据查询规则
	 * @return	array
	 */
	public function findAll($param)
	{
	
	}

	/**
	 * 统计数据
	 *
	 * @access	public
	 * @param	string	$tableKey	数据表标识
	 * @param	array	$rule		数据查询规则
	 * @return	int
	 */
	public function count($param)
	{
		$param = $this->combined( $param );
		
		$sql = 'SELECT COUNT('.$param['count'].') AS total FROM `'.$this->tablePrefix().'` WHERE '.$param['where'];
		
		return $this->query($sql)->fetch();
	}
	
	/**
	 * 创建一条数据
	 *
	 * @access	public
	 * @param	array	$param		数据创建规则
	 * @return	int     0失败、大于0成功
	 */
	public function create($param)
	{
		$sql = 'INSERT INTO `'.$this->tablePrefix().'` '.$this->deal($param).';';
		
		return $this->exec($sql) ? $this->pdo->lastInsertId() : false;
	}
	
	/**
	 * 修改数据
	 *
	 * @access	public
	 * @param	string	$tableKey	数据表标识
	 * @param	array	$data		数据信息[键值对]
	 * @param	array	$rule		数据修改规则
	 * @return	bool
	 */
	public function modify($param)
	{
		$param = $this->combined( $param );
		
		$sql   = 'UPDATE `'.$this->tablePrefix().'` SET '.$param['set'].' WHERE '.$param['where'].';';
		
		return $this->exec($sql) ? $this->pdo->lastInsertId() : false;
	}

	/**
	 * 删除数据 
	 *
	 * @access	public
	 * @param	array	$param		数据删除规则
	 * @return	bool
	 */
	public function remove($param)
	{
		$param = $this->combined( $param );
		
		$where = !empty($param['in']) ? $param['in'] :  $param['where'] ;
		
		$sql = 'DELETE FROM `'.$this->tablePrefix().'` WHERE '.$where;
		
		return $this->exec($sql) ? $this->pdo->lastInsertId() : false;
	}
	
/**
	 *  处理(查询)数组数据
	 * 
	 * @param array $param
	 */
	private function combined( $param )
	{
		
		$r = array(
			'col'   => null,
			'set'   => null,
			'where' => null,
			'in'    => null,
			'group' => null,
			'order' => null,
			'limit' => null,
			'count' => null,
			'pageRows' => null,
			'point'    => null,
		); 
		
		//处理查询字段
		if(isset($param['col']) && !empty($param['col'])) {
			
			$r['col'] = $param['col'];
		}
		
		//处理修改字段
		if(isset($param['set']) && !empty($param['set'])) {
			
			$r['set'] .= $this->where( $param['set'] );
		}
		
		//处理where条件字段
		if(isset($param['where']) && !empty($param['where'])) {
			
			$r['where'] .= $this->where( $param['where'] );
		}
		
		//处理in条件字段(尽量少用)
		if(isset($param['in']) && !empty($param['in'])) {

			$str = $keys = null;
			
			foreach ($param['in'] as $key=>$val) {
				
				$keys .= $key;
			}
			if(empty($keys)) {return false;}
			foreach ($param['in'][$keys] as $val) {
				
				$str .= $val.",";
			}
			$r['in'] = $keys.' in ('.trim($str ,',').')';
		}
		
		//处理group条件字段
		if(isset($param['group']) && !empty($param['group'])) {
			
			$r['group'] .= 'GROUP BY '.$param['group'];
		}
		
		//处理order条件字段
		if(isset($param['order']) && !empty($param['order'])) {
			
			$desc        = isset($param['desc']) && !empty($param['desc']) ? $param['desc'] : 'ASC';
			$r['order'] .= 'ORDER BY '.$param['order'].' '.$desc;
		}
		
		//处理limit条件字段
		if(isset($param['limit']) && !empty($param['limit'])) {
			
			$limit       = isset($param['limit']) && !empty($param['limit']) ? $param['limit'] : 1;
			$r['limit'] .= 'LIMIT '.$limit;
		}
		
		//处理limit条件字段
		if(isset($param['count']) && !empty($param['count'])) {
			
			$limit       = isset($param['count']) && !empty($param['count']) ? $param['count'] : '*';
			$r['count'] .= $limit;
		}
		
		//处理分页显示条件
		if(isset($param['pageRows']) && !empty($param['pageRows'])) {
			
			$r['pageRows'] .= $param['pageRows'];
		}
		
		//分页数
		if(isset($param['point']) && !empty($param['point'])) {
			
			$r['point'] .= $param['point'];
		}
		
		//同时判断
		if(isset($param['symbol']) && !empty($param['symbol'])) {
			
			$str          = $param['symbol'];
			$bol          = !empty($str['than']) ? $str['link'].' '.$str['than'] : '';
			$r['symbol'] .= $str['larger'].' '.$bol;
		}

		return $r;
	}
	
	/**
	 * 处理(where)组合语句
	 * 
	 * @param array $param
	 */
	private function where ( $param )
	{
		$str = null;	
		foreach ($param as $key =>$val) {
			if(is_int($val)) {
				
				$str .= "`{$key}` = {$val} ";
			} else {
				$str .= "`{$key}` =  '{$val}' ";
			}
		}
		
		return $str;
	}
	
	/**
	 * 处理(插入)数组数据
	 * 
	 */
	private function deal( $param )
	{
		$keys = $value = $vals = null;
		foreach( $param as $key => $val ) {
			
			$keys .=  "`".$key."`,";
			$vals .=  "'".$val."',";
		}
		
		$keys  = trim($keys , ',');
		$vals  = trim($vals , ',');
		$value = "({$keys}) VALUE ({$vals})";
		return $value;
	}
	
	/**
	 * 析构函数
	 */
	public function __destruct()
	{
		unset($this->pdo);
		unset($this->configFile);
		unset($this->tableKey);
	}

                   

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php 简单的路由器Nächster Artikel:php单例模式