search
Homephp教程PHP源码Mysql PDO基础操作
Mysql PDO基础操作May 23, 2016 pm 05:10 PM


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);
	}

                   

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor