php封装的pdo数据库操作工具类与用法示例
本文实例讲述了php封装的pdo数据库操作工具类与用法。分享给大家供大家参考,具体如下:
'localhost', 'username'=>'root', 'password'=>'1234', 'database'=>'test', 'hostport'=>'3306', 'dbms'=>'mysql', 'dsn'=>'mysql:host=localhost;dbname=test' ); } if(empty($dbConfig['hostname'])){ self::throw_exception("没有定义数据库配置,请先定义"); } self::$config=$dbConfig; if(empty(self::$config['params'])){ self::$config['params']=array(); } if(!isset(self::$link)){ $configs=self::$config; if(self::$pconnect){ //开启长连接,添加到配置数组中 $configs['params'][constant("PDO::ATTR_PERSISTENT")]=true; } try{ self::$link=newPDO($configs['dsn'],$configs['username'],$configs['password'],$configs['params']); }catch(PDOException$e){ self::throw_exception($e->getMessage()); } if(!self::$link){ self::throw_exception("PDO连接错误"); returnfalse; } self::$link->exec("setnamesutf8"); self::$dbVersion=self::$link->getAttribute(constant("PDO::ATTR_SERVER_VERSION")); unset($configs); } } /** *得到所有记录 * *@param$sqlThesql * *@return All. */ publicstaticfunctiongetAll($sql=null){ if($sql!=null){ self::query($sql); } $result=self::$PDOStatement->fetchAll(constant("PDO::FETCH_ASSOC")); return$result; } /** *得到一条记录 * *@param $sqlThesql * *@return Therow. */ publicstaticfunctiongetRow($sql=null){ if($sql!=null){ self::query($sql); } $result=self::$PDOStatement->fetch(constant("PDO::FETCH_ASSOC")); return$result; } /** *执行增删改操作,返回受影响记录的条数 * *@param $sqlThesql * *@returnboolean(description_of_the_return_value) */ publicstaticfunctionexecute($sql=null){ $link=self::$link; if(!$link)returnfalse; if($sql!=null){ self::$queryStr=$sql; } if(!empty(self::$PDOStatement))self::free(); $result=$link->exec(self::$queryStr); self::haveErrorThrowException(); if($result){ self::$lastInsertId=$link->lastInsertId(); self::$numRows=$result; return$result; }else{ returnfalse; } } /** *根据主键查找记录 * *@param $tabNameThetabname *@param $priIdThepriidentifier *@paramstring$fieldsThefields * *@return (description_of_the_return_value) */ publicstaticfunctionfindById($tabName,$priId,$fields='*'){ $sql='SELECT%sFROM%sWHEREid=%d'; returnself::getRow(sprintf($sql,self::parseFields($fields),$tabName,$priId)); } /** *执行普通查询 * *@param $tablesThetables *@param $whereThewhere *@paramstring$fieldsThefields *@param $groupThegroup *@param $havingThehaving *@param $orderTheorder *@param $limitThelimit * *@return (description_of_the_return_value) */ publicstaticfunctionfind($tables,$where=null,$fields='*',$group=null,$having=null,$order=null,$limit =null){ $sql='SELECT'.self::parseFields($fields).'FROM'.$tables .self::parseWhere($where) .self::parseGroup($group) .self::parseHaving($having) .self::parseOrder($order) .self::parseLimit($limit); $data=self::getAll($sql); return$data; } /** *添加记录 * *@param $dataThedata *@param $tableThetable * *@return (description_of_the_return_value) */ publicstaticfunctionadd($data,$table){ $keys=array_keys($data); array_walk($keys,array('PdoMySQL','addSpecialChar')); $fieldsStr=join(',',$keys); $values="'".join("','",array_values($data))."'"; $sql="INSERT{$table}({$fieldsStr})VALUES({$values})"; returnself::execute($sql); } /** *更新数据 * *@param $dataThedata *@param $tableThetable *@param $whereThewhere *@param $orderTheorder *@param $limitThelimit */ publicstaticfunctionupdate($data,$table,$where=null,$order=null,$limit=null){ $sets=''; foreach($dataas$key=>$value){ $sets.=$key."='".$value."',"; } $sets=rtrim($sets,','); $sql="UPDATE{$table}SET{$sets}".self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit); echo$sql; } /** *删除数据 * *@param $dataThedata *@param $tableThetable *@param $whereThewhere *@param $orderTheorder *@param $limitThelimit * *@return (description_of_the_return_value) */ publicstaticfunctiondelete($table,$where=null,$order=null,$limit=null){ $sql="DELETEFROM{$table}".self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit); returnself::execute($sql); } /** *执行查询 * *@paramstring$sqlThesql * *@returnboolean(description_of_the_return_value) */ publicstaticfunctionquery($sql=''){ $link=self::$link; if(!$link)returnfalse; //判断之前是否有结果集,如果有的话,释放结果集 if(!empty(self::$PDOStatement))self::free(); self::$queryStr=$sql; self::$PDOStatement=$link->prepare(self::$queryStr); $res=self::$PDOStatement->execute(); self::haveErrorThrowException(); return$res; } /** *获取最后执行的sql * *@returnbooleanThelastsql. */ publicstaticfunctiongetLastSql(){ $link=self::$link; if(!$link){ returnfalse; } returnself::$queryStr; } /** *获取最后插入的ID * *@returnbooleanThelastinsertidentifier. */ publicstaticfunctiongetLastInsertId(){ $link=self::$link; if(!$link){ returnfalse; } returnself::$lastInsertId; } /** *获得数据库的版本 * *@returnbooleanThedatabaseversion. */ publicstaticfunctiongetDbVersion(){ $link=self::$link; if(!$link){ returnfalse; } returnself::$dbVersion; } /** *得到数据库中表 * *@returnarray(description_of_the_return_value) */ publicstaticfunctionshowTables(){ $tables=array(); if(self::query("showtables")){ $result=self::getAll(); foreach($resultas$key=>$value){ $tables[$key]=current($value); } } return$tables; } /** *解析where条件 * *@param $whereThewhere * *@return (description_of_the_return_value) */ publicstaticfunctionparseWhere($where){ $whereStr=''; if(is_string($where)&&!empty($where)){ $whereStr=$where; } returnempty($whereStr)?'':'WHERE'.$whereStr; } /** *解析group * *@param $groupThegroup * *@return (description_of_the_return_value) */ publicstaticfunctionparseGroup($group){ $groupStr=''; if(is_array($group)){ $groupStr=implode(',',$group); }elseif(is_string($group)&&!empty($group)){ $groupStr=$group; } returnempty($groupStr)?'':'GROUPBY'.$groupStr; } /** *解析having * *@param $havingThehaving * *@return (description_of_the_return_value) */ publicstaticfunctionparseHaving($having){ $havingStr=''; if(is_string($having)&&!empty($having)){ $havingStr=$having; } returnempty($havingStr)?'':'HAVING'.$havingStr; } /** *解析order * *@param $orderTheorder * *@return (description_of_the_return_value) */ publicstaticfunctionparseOrder($order){ $orderStr=''; if(is_string($order)&&!empty($order)){ $orderStr=$order; } returnempty($orderStr)?'':'ORDERBY'.$orderStr; } /** *解析limit * *@param $limitThelimit * *@return (description_of_the_return_value) */ publicstaticfunctionparseLimit($limit){ $limitStr=''; if(is_array($limit)){ $limitStr=implode(',',$limit); }elseif(is_string($limit)&&!empty($limit)){ $limitStr=$limit; } returnempty($limitStr)?'':'LIMIT'.$limitStr; } /** *解析字段 * *@param $fieldsThefields * *@returnstring(description_of_the_return_value) */ publicstaticfunctionparseFields($fields){ if(is_array($fields)){ array_walk($fields,array('PdoMySQL','addSpecialChar')); $fieldsStr=implode(',',$fields); }elseif(is_string($fields)&&!(empty($fields))){ if(strpos($fields,'`')===false){ $fields=explode(',',$fields); array_walk($fields,array('PdoMySQL','addSpecialChar')); $fieldsStr=implode(',',$fields); }else{ $fieldsStr=$fields; } }else{ $fieldsStr="*"; } return$fieldsStr; } /** *通过反引号引用字字段 * *@paramstring$valueThevalue * *@returnstring(description_of_the_return_value) */ publicstaticfunctionaddSpecialChar(&$value){ if($value==="*"||strpos($value,'.')!==false||strpos($value,'`')!==false){ //不用做处理 }elseif(strpos($value,'`')===false){ $value='`'.trim($value).'`'; } return$value; } /** *释放结果集 */ publicstaticfunctionfree(){ self::$PDOStatement=null; } /** *抛出错误信息 * *@returnboolean(description_of_the_return_value) */ publicstaticfunctionhaveErrorThrowException(){ $obj=empty(self::$PDOStatement)?self::$link:self::$PDOStatement; $arrError=$obj->errorInfo(); if($arrError[0]!='00000'){ self::$error='SQLSTATE=>'.$arrError[0].'
SQLError=>'.$arrError[2].'
ErrorSQL=>'.self::$queryStr; self::throw_exception(self::$error); returnfalse; } if(self::$queryStr==''){ self::throw_exception('没有执行SQL语句'); returnfalse; } } /** *自定义错误处理 * *@param$errMsgTheerrormessage */ publicstaticfunctionthrow_exception($errMsg){ echo$errMsg; } /** *销毁连接对象,关闭数据库 */ publicstaticfunctionclose(){ self::$link=null; } } $pdo=newPdoMysql(); var_dump($pdo->showTables());
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP基于pdo操作数据库技巧总结》、《php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。