PHP データベース操作クラスのソース コード

WBOY
リリース: 2016-06-21 08:57:23
オリジナル
1289 人が閲覧しました

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

}

/*打印错误*/
static function throwError($errmsg){
echo '

error:'.$errmsg.'

';
    exit();
  }
}
?>
class db{
private $result = array();
private $connector = array();
private $configs = array();
private $active = 0;
private $default_config = array(
'dbtype' => 'mysql',
          'index' => 0,'user' => 'root', 'pwd' => '' ,'host' => 'localhost' ,'port'=> 3306,'charset' => 'utf8' ,'dbname' => null
    );
   
   /*初始化*/
   public function __construct($config = array()){
     if($config) $this->connect($config);
   }

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

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

     $config = Core::inHerit($this->default_config,$config);
     !in_array($config['dbtype'],array('mysql')) &&  Core::throwError('未支持的数据库类型');
     extract($config);
     $this->configs[$index] = $config;
     $this->{'_'.$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->connector[$index] =  mysqli_connect ( $host, $user, $pwd , null, $port) or Core::throwError(mysql_error());
     $this->active = $index;
     if($dbname) $this->selectDb($dbname,$charset);
   }
  
   /*取得当前连接*/
   private function _getConnect(){
     return $this->connector[$this->active];
   }
   /*取得当前连接使用的数据库类型 带参数自动拼接为函数名*/
   private function _getDbTypeFunc($funcname = null){
     $dbtype = $this->configs[$this->active]['dbtype'];
     return $funcname?'_'.$dbtype.'_'.$funcname:$dbtype;
   }
   /*选择数据库*/
   public function selectDb($dbname,$charset){
     mysqli_select_db($this->_getConnect(),$dbname) or Core::throwError(mysql_error());
     $this->_mysql_query('set names '.$charset);
   }
  
   /*执行语句*/
   private function _mysql_query($sql){
    $result = mysqli_query($this->_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->_getConnect(),$sql) or Core::throwError('wrong sql:'.$sql);
       
       
        $ptype = '';
        $bindparam = array($stmt,'');
   
        foreach ($sqlv as $k => $v){
            $ptype .= $this->_getParamType($k);
            $bindparam[] = $v;
            }
        $bindparam[1] = $ptype;
   
        call_user_func_array('mysqli_stmt_bind_param',$bindparam);
        return $this->_mysql_stmt_exec($stmt,$sql);
   }

   private function _mysql_bind_in_sort(){
       $argus = func_get_args() ;
       $sql = array_shift($argus);
       $stmt = mysqli_prepare($this->_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->_mysql_stmt_exec($stmt,$sql);
   }

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

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

/*パラメータ形式に従って異なる関数を使用します*/
private function _mysql_iquery($sql, $sqlv = array()){
if ($sqlv){
if (is_array($ sqlv) )
_ _func_array(array) ($this,'_mysql_bind_in_sort'), $argus);
}
}else{
} return $this->_mysql_query($sql,$sqlv );
}
}

/*キーに従って、名前の接頭辞によってデータ型が区別されます*/
プライベート関数 _getParamType($key){
$r = 's ';
/*最初の文字が小文字で 2 番目の文字が大文字の場合、最初の文字はパターンのプレフィックスです* /
$mode = array(
'i' => 'i', 's' => 's','d' => 'd','b' => b '
);
if (strlen($key) >= 2 && $ key[0] == strto lower($key[0]) && $key[1] == strtoupper($key[1 ]) && in_array($key[0],$mode))
$r = $ mode[$key[0]]; SQL ステートメントを分析して動作を決定する*/
private function _cmdType($sql){
return substr(strto lower( $sql),0,strpos($sql,' ') );

}
/*SQL ステートメントが select ステートメントであるかどうかを分析します*/
private function isSelect($sql){
return 'select' == $this-> _cmdType($sql);
}
パブリック関数 query($sql, $sqlv = array()){
$func = $this->_getDbTypeFunc('iquery');

$argus = func_get_args();
$argus[0] = trim($argus[0]);
return call_user_func_array(array($this,$func),$argus);
}

}
?> ;

$d = array(
'dbname' => 'test',
'charset' => 'latin1'
);
$db = 新しいデータベース($d);

//配列モードでパラメータをバインドします
$sqlv = array('iId1'=>'14','id2' => 30);
$r = $db -> "id > :iId1 および id から ID を選択します。
//パラメータをバインドする標準的な方法
$r = $db -> query("select content from toselect where id > ? ",13);

var_dump($r);
?>



関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のおすすめ
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!