当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP实现的数据库封装类

PHP
php 多线程上下文中安全写文件实现代码
PHP类的使用 实例代码讲解
用php实现让页面只能被百度gogole蜘蛛访问的方法
php 学习笔记
PHP编程过程中需要了解的this,self,parent的区别
php 操作excel文件的方法小结
使用PHP获取网络文件的实现代码
PHP 巧用数组降低程序的时间复杂度
php下将XML转换为数组
php 文件上传代码(限制jpg文件)
php 无极分类(递归)实现代码
PHP 采集获取指定网址的内容
PHP 将图片按创建时间进行分类存储的实现代码
PHP 存储文本换行实现方法
PHP 批量更新网页内容实现代码
用PHP查询搜索引擎排名位置的代码
用php实现的获取网页中的图片并保存到本地的代码
php实现首页链接查询 友情链接检查的代码
处理php自动反斜杠的函数代码
php实现的遍历文件夹下所有文件,编辑删除

PHP实现的数据库封装类


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 81 ::
收藏到网摘: n/a

 PHP学习实例,数据库封装类。

<?php
class Core{
  /*对数组进行继承*/
  static function inHerit($arr_orgin,$arr_output){
    return array_merge($arr_orgin,$arr_output);
 
  }

  /*打印错误*/
  static function throwError($errmsg){
    echo '&lt;p>error:'.$errmsg.'</p>';
    exit();
  }
}
?>
<?php
class db{
    private $result = array();
    private $connector = array();
    private $configs = array();
    private $active = 0;
    private $default_config = array(
        'dbtype' => 'mysql',
          'index' =&gt; 0,'user' =&gt; 'root', 'pwd' =&gt; '' ,'host' =&gt; 'localhost' ,'port'=&gt; 3306,'charset' =&gt; 'utf8' ,'dbname' =&gt; null
    );
   
   /*初始化*/
   public function __construct($config = array()){
     if($config) $this-&gt;connect($config);
   }

   public function __destruct(){
       foreach($this-&gt;connector as $index =&gt; $connect)
           $this-&gt;{'_'.$this-&gt;configs[$index]['dbtype'].'_close'}($connect);
           
   }

   private function _mysql_close($connect){
      mysqli_close($connect);
   }
   /*选择连接*/
   public function selectConnect($index){
        return  isset($this-&gt;connector[$index]) && (($this-&gt;active = $index) || true);
   }
   /*建立连接*/
   public function connect($config){
     (!isset($config['index'])) && $config['index'] = $this-&gt;default_config['index']++  ;

     $config = Core::inHerit($this-&gt;default_config,$config);
     !in_array($config['dbtype'],array('mysql')) &&  Core::throwError('未支持的数据库类型');
     extract($config);
     $this-&gt;configs[$index] = $config;
     $this-&gt;{'_'.$config['dbtype'].'_connect'}($user, $pwd,$host,$dbname,$charset,$index,$port);
   
   }
   private function _mysql_connect($user = 'root', $pwd = '' ,$host = 'localhost' ,$dbname = null,$charset = 'utf8' ,$index = 0 ,$port = 3306){
     $this-&gt;connector[$index] =  mysqli_connect ( $host, $user, $pwd , null, $port) or Core::throwError(mysql_error());
     $this-&gt;active = $index;
     if($dbname) $this-&gt;selectDb($dbname,$charset);
   }
  
   /*取得当前连接*/
   private function _getConnect(){
     return $this-&gt;connector[$this-&gt;active];
   }
   /*取得当前连接使用的数据库类型 带参数自动拼接为函数名*/
   private function _getDbTypeFunc($funcname = null){
     $dbtype = $this-&gt;configs[$this-&gt;active]['dbtype'];
     return $funcname?'_'.$dbtype.'_'.$funcname:$dbtype;
   }
   /*选择数据库*/
   public function selectDb($dbname,$charset){
     mysqli_select_db($this-&gt;_getConnect(),$dbname) or Core::throwError(mysql_error());
     $this-&gt;_mysql_query('set names '.$charset);
   }
  
   /*执行语句*/
   private function _mysql_query($sql){
    $result = mysqli_query($this-&gt;_getConnect(),$sql) or Core::throwError(mysql_error());
    return $result;
   }

   private function _mysql_bind_by_name($sql , $sqlv){
        $sql_param = array();
       
        $getparam = $getparam2 =   '\w+?';// $getparam = array_keys($sqlv); implode('|',$getparam);
        preg_match_all('/:('.$getparam.')\b/iU',$sql,$getparam) or   Core::throwError('参数绑定错误');
       
        $getparam = $getparam[1];
        $getparam = array_flip($getparam);

        count($getparam) != count($sqlv) || array_diff_key($getparam,$sqlv) &&  Core::throwError('参数不匹配');

        $sql = preg_replace('/:('.$getparam2.')\b/iU','?',$sql)  ;
               
        $sqlv = array_merge($getparam,$sqlv);
       
        unset($getparam2);
        unset($getparam);
       
       
        $stmt = mysqli_prepare($this-&gt;_getConnect(),$sql) or Core::throwError('wrong sql:'.$sql);
       
       
        $ptype = '';
        $bindparam = array($stmt,'');
   
        foreach ($sqlv as $k =&gt; $v){
            $ptype .= $this-&gt;_getParamType($k);
            $bindparam[] = $v;
            }
        $bindparam[1] = $ptype;
   
        call_user_func_array('mysqli_stmt_bind_param',$bindparam);
        return $this-&gt;_mysql_stmt_exec($stmt,$sql);
   }

   private function _mysql_bind_in_sort(){
       $argus = func_get_args() ;
       $sql = array_shift($argus);
       $stmt = mysqli_prepare($this-&gt;_getConnect(),$sql) or Core::throwError('wrong sql:'.$sql);
       $pcount = mysqli_stmt_param_count($stmt);
      
       $pcount != count($argus)  && Core::throwError('参数不匹配');
       $ptype = str_repeat('s',$pcount);
       array_splice($argus, 0, 0 ,array($stmt,$ptype));
       call_user_func_array('mysqli_stmt_bind_param',$argus);

       return $this-&gt;_mysql_stmt_exec($stmt,$sql);
   }

   private function _mysql_stmt_exec($stmt,$sql){
         mysqli_stmt_execute($stmt);

        if($this-&gt;isSelect($sql)){ ///返回值绑定
           
            mysqli_stmt_bind_result($stmt,$a);
             while ($stmt-&gt;fetch()) {
                    print_r($a);
                    echo '<br/>';
                }
         }
         $stmt-&gt;close();
  
   }

   /*根据参数形式使用不同函数*/
   private function _mysql_iquery($sql , $sqlv = array()){
     if ($sqlv){
         if (is_array($sqlv))
             return  $this-&gt;_mysql_bind_by_name($sql , $sqlv);
         else{
             $argus = func_get_args() ;
             return call_user_func_array(array($this,'_mysql_bind_in_sort'),$argus);
         }
     }else{
         return $this-&gt;_mysql_query($sql,$sqlv);
     }
   }
 
  /*根据键名前缀区分数据类型*/
  private function _getParamType($key){
     $r = 's';
     /*首字母小写 第二个字母大写 则第一个字母为模式前缀*/
     $mode = array(
       'i' =&gt; 'i','s' =&gt; 's','d' =&gt; 'd','b' =&gt; 'b'   
     );
     if (strlen($key) &gt;= 2 &&  $key[0] == strtolower($key[0]) && $key[1] == strtoupper($key[1]) && in_array($key[0],$mode))
        $r = $mode[$key[0]];
   
     return $r;
  }
 /*分析sql语句 判断行为*/
  private function _cmdType($sql){
      return substr(strtolower($sql),0,strpos($sql,' '));
       
   }
   /*分析sql语句是否为select语句*/
   private function isSelect($sql){
        return  'select' == $this-&gt;_cmdType($sql);
   }
   public function query($sql , $sqlv = array()){
       $func = $this-&gt;_getDbTypeFunc('iquery');
      
       $argus = func_get_args() ;
       $argus[0] = trim($argus[0]);
       return call_user_func_array(array($this,$func),$argus);
   }
 
}
?>

<?php
$d = array(
  'dbname' => 'test',
  'charset' =&gt; 'latin1'
  );
$db = new db($d);

//数组方式绑定参数
$sqlv = array('iId1'=&gt;'14','id2' =&gt; 30);
$r = $db -&gt; query("select id from toselect where   id &gt; :iId1 and id < :id2 ",$sqlv);

//标准方式绑定参数
$r = $db -> query("select content from toselect where   id &gt; ? ",13);

var_dump($r);
?>