php封装的数据库函数与用法示例【参考thinkPHP】
本文实例讲述了php封装的数据库函数与用法。分享给大家供大家参考,具体如下:
从Thinkphp里面抽离出来的数据库模块,感觉挺好用
common.php:
<?PHP /** *通用函数 */ //包含配置文件 if(is_file("config.php")){ C(include'config.php'); } if(!function_exists("__autoload")){ function__autoload($class_name){ require_once('classes/'.$class_name.'.class.php'); } } /** *数据库操作函数 *@return\mysqli */ functionM(){ $db=newModel(); if(mysqli_connect_errno()) throw_exception(mysqli_connect_error()); return$db; } //获取配置值 functionC($name=null,$value=null){ //静态全局变量,后面的使用取值都是在$)config数组取 static$_config=array(); //无参数时获取所有 if(empty($name)) return$_config; //优先执行设置获取或赋值 if(is_string($name)){ if(!strpos($name,'.')){ $name=strtolower($name); if(is_null($value)) returnisset($_config[$name])?$_config[$name]:null; $_config[$name]=$value; return; } //二维数组设置和获取支持 $name=explode('.',$name); $name[0]=strtolower($name[0]); if(is_null($value)) returnisset($_config[$name[0]][$name[1]])?$_config[$name[0]][$name[1]]:null; $_config[$name[0]][$name[1]]=$value; return; } //批量设置 if(is_array($name)){ return$_config=array_merge($_config,array_change_key_case($name)); } returnnull;//避免非法参数 } functionajaxReturn($data=null,$message="",$status){ $ret=array(); $ret["data"]=$data; $ret["message"]=$message; $ret["status"]=$status; echojson_encode($ret); die(); } //调试数组 function_dump($var){ if(C("debug")) dump($var); } //浏览器友好的变量输出 functiondump($var,$echo=true,$label=null,$strict=true){ $label=($label===null)?'':rtrim($label).''; if(!$strict){ if(ini_get('html_errors')){ $output=print_r($var,true); $output='<pre>'.$label.htmlspecialchars($output,ENT_QUOTES).'</pre>'; }else{ $output=$label.print_r($var,true); } }else{ ob_start(); var_dump($var); $output=ob_get_clean(); if(!extension_loaded('xdebug')){ $output=preg_replace("/\]\=\>\n(\s+)/m",']=>',$output); $output='<pre>'.$label.htmlspecialchars($output,ENT_QUOTES).'</pre>'; } } if($echo){ echo($output); returnnull; } else return$output; } /** *调试输出 *@paramtype$msg */ function_debug($msg){ if(C("debug")) echo"$msg<br/>"; } function_log($filename,$msg){ $time=date("Y-m-dH:i:s"); $msg="[$time]\n$msg\r\n"; if(C("log")){ $fd=fopen($filename,"a+"); fwrite($fd,$msg); fclose($fd); } } /** *日志记录 *@paramtype$str */ functionL($msg){ $time=date("Y-m-dH:i:s"); $clientIP=$_SERVER['REMOTE_ADDR']; $msg="[$time$clientIP]$msg\r\n"; $log_file=C("LOGFILE"); _log($log_file,$msg); } ?>
config.php:
<?php /** *数据库配置文件 */ $db=array( 'DB_TYPE'=>'mysql', 'DB_HOST'=>'127.0.0.1', 'DB_NAME'=>'DB', 'DB_USER'=>'USER', 'DB_PWD'=>'PWD', 'DB_PORT'=>'3306', ); return$db; ?>
数据库模型类Model.class.php,放到classes/目录下:
<?php /** *数据库模型类 */ classModel{ //数据库连接ID支持多个连接 protected$linkID=array(); //当前数据库操作对象 protected$db=null; //当前查询ID protected$queryID=null; //当前SQL指令 protected$queryStr=''; //是否已经连接数据库 protected$connected=false; //返回或者影响记录数 protected$numRows=0; //返回字段数 protected$numCols=0; //最近错误信息 protected$error=''; publicfunction__construct(){ $this->db=$this->connect(); } /** *连接数据库方法 */ publicfunctionconnect($config='',$linkNum=0){ if(!isset($this->linkID[$linkNum])){ if(empty($config)) $config=array( 'username'=>C('DB_USER'), 'password'=>C('DB_PWD'), 'hostname'=>C('DB_HOST'), 'hostport'=>C('DB_PORT'), 'database'=>C('DB_NAME') ); $this->linkID[$linkNum]=newmysqli($config['hostname'],$config['username'],$config['password'],$config['database'],$config['hostport']?intval($config['hostport']):3306); if(mysqli_connect_errno()) throw_exception(mysqli_connect_error()); $this->connected=true; } return$this->linkID[$linkNum]; } /** *初始化数据库连接 */ protectedfunctioninitConnect(){ if(!$this->connected){ $this->db=$this->connect(); } } /** *获得所有的查询数据 *@accessprivate *@paramstring$sqlsql语句 *@returnarray */ publicfunctionselect($sql){ $this->initConnect(); if(!$this->db) returnfalse; $query=$this->db->query($sql); $list=array(); if(!$query) return$list; while($rows=$query->fetch_assoc()){ $list[]=$rows; } return$list; } /** *只查询一条数据 */ publicfunctionfind($sql){ $resultSet=$this->select($sql); if(false===$resultSet){ returnfalse; } if(empty($resultSet)){//查询结果为空 returnnull; } $data=$resultSet[0]; return$data; } /** *获取一条记录的某个字段值,sql由自己组织 *例子:$model->getField("selectidfromuserlimit1") */ publicfunctiongetField($sql){ $resultSet=$this->select($sql); if(!empty($resultSet)){ returnreset($resultSet[0]); } } /** *执行查询返回数据集 */ publicfunctionquery($str){ $this->initConnect(); if(!$this->db){ if(C("debug")) echo"connecttodatabaseerror"; returnfalse; } $this->queryStr=$str; //释放前次的查询结果 if($this->queryID) $this->free(); $this->queryID=$this->db->query($str); //对存储过程改进 if($this->db->more_results()){ while(($res=$this->db->next_result())!=NULL){ $res->free_result(); } } //$this->debug(); if(false===$this->queryID){ echo$this->error(); returnfalse; }else{ $this->numRows=$this->queryID->num_rows; $this->numCols=$this->queryID->field_count; return$this->getAll(); } } /** *执行语句,例如插入,更新操作 *@accesspublic *@paramstring$strsql指令 *@returninteger */ publicfunctionexecute($str){ $this->initConnect(); if(!$this->db) returnfalse; $this->queryStr=$str; //释放前次的查询结果 if($this->queryID) $this->free(); $result=$this->db->query($str); if(false===$result){ $this->error(); returnfalse; }else{ $this->numRows=$this->db->affected_rows; $this->lastInsID=$this->db->insert_id; return$this->numRows; } } /** *获得所有的查询数据 *@accessprivate *@paramstring$sqlsql语句 *@returnarray */ privatefunctiongetAll(){ //返回数据集 $result=array(); if($this->numRows>0){ //返回数据集 for($i=0;$i<$this->numRows;$i++){ $result[$i]=$this->queryID->fetch_assoc(); } $this->queryID->data_seek(0); } return$result; } /** *返回最后插入的ID */ publicfunctiongetLastInsID(){ return$this->db->insert_id; } //返回最后执行的sql语句 publicfunction_sql(){ return$this->queryStr; } /** *数据库错误信息 */ publicfunctionerror(){ $this->error=$this->db->errno.':'.$this->db->error; if(''!=$this->queryStr){ $this->error.="\n[SQL语句]:".$this->queryStr; } //trace($this->error,'','ERR'); return$this->error; } /** *释放查询结果 */ publicfunctionfree(){ $this->queryID->free_result(); $this->queryID=null; } /** *关闭数据库 */ publicfunctionclose(){ if($this->db){ $this->db->close(); } $this->db=null; } /** *析构方法 */ publicfunction__destruct(){ if($this->queryID){ $this->free(); } //关闭连接 $this->close(); } }
例子:
#include"common.php" functiontest(){ $model=M(); $sql="select*fromtest"; $list=$model->query($sql); _dump($list); }
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php面向对象程序设计入门教程》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。