非常に実用的なphpデータベースpdo操作クラス(curd操作クラス)

10330 ワード

操作クラスファイル
db.class.php
pdo = new PDO("mysql:host=".$config['db_host'].";port=".$config['db_port'].";dbname=".$config['db_name'],$config['db_user'], $config['db_pass']); 
        }catch(PDOException $e){
            //        ,         ,       !
            exit($e->getMessage());
        }
        $this->prefix = $config['db_prefix'];
        $this->pdo->exec("SET NAMES UTF8");
        
        
    }
    //      
    public function set_table($table=null,$primary='id'){
        if($table==null){ exit('Not found Table');}
        
        $this->primary = $primary;
        $this->table = $this->prefix.$table;
        return $this;
    }
    
    
    //     
    public function getData($sql)
    {
        if(!$result = $this->query($sql))return array();
        if(!$this->Statement->rowCount())return array();
        $rows = array();
        while($rows[] = $this->Statement->fetch(PDO::FETCH_ASSOC)){}
        $this->Statement=null;
        array_pop($rows);
        return $rows;
    }
    
    //       
    public function getCount($conditions){
        $where = '';
        if(is_array($conditions)){
            $join = array();
            foreach( $conditions as $key => $value ){
                $value =  '\''.$value.'\'';
                $join[] = "{$key} = {$value}";
            }
            $where = "WHERE ".join(" AND ",$join);
        }else{
            if(null != $conditions)$where = "WHERE ".$conditions;
        }
        $sql = "SELECT count(*) as Frcount FROM {$this->table} {$where}";
        $result = $this->getData($sql);
        return $result[0]['Frcount'];
        
    }
    //         
    public function getField($where=null,$fields=null){
        if( $record = $this->findAll($where, null, $fields, 1) ){
            $res = array_pop($record);
            return $res[$fields];
        }else{
            return FALSE;
        }
    }
    //     
    public function goInc($conditions,$field,$vp=1){
        $where = "";
        if(is_array($conditions)){
            $join = array();
            foreach( $conditions as $key => $value ){
                $value = '\''.$value.'\'';
                $join[] = "{$key} = {$value}";
            }
            $where = "WHERE ".join(" AND ",$join);
        }else{
            if(null != $conditions)$where = "WHERE ".$conditions;
        }
        $values = "{$field} = {$field} + {$vp}";
        $sql = "UPDATE {$this->table} SET {$values} {$where}";
        
        return $this->pdo->exec($sql);
        
    }
    
    //   
    public function goDec($conditions,$field,$vp=1){
        return $this->goInc($conditions,$field,-$vp);
    }
    
    //     
    public function update($conditions,$row)
    {
        $where = "";
        $row = $this->__prepera_format($row);
        if(empty($row)){
        return FALSE;
        }
        if(is_array($conditions)){
            $join = array();
            foreach( $conditions as $key => $condition ){
                $condition = '\''.$condition.'\'';
                $join[] = "{$key} = {$condition}";
            }
            $where = "WHERE ".join(" AND ",$join);
        }else{
            if(null != $conditions){
              $where = "WHERE ".$conditions;
            }
        }
        foreach($row as $key => $value){
            $value = '\''.$value.'\'';
            $vals[] = "{$key} = {$value}";
        }
        $values = join(", ",$vals);
        $sql = "UPDATE {$this->table} SET {$values} {$where}";
        //echo $sql.'
'; $res = $this->pdo->exec($sql); if($res){ return $res; }else{ var_dump($this->pdo->errorInfo()); } } // public function findAll($conditions=null,$order=null,$fields=null,$limit=null) { $where = ''; if(is_array($conditions)){ $join = array(); foreach( $conditions as $key => $value ){ $value = '\''.$value.'\''; $join[] = "{$key} = {$value}"; } $where = "WHERE ".join(" AND ",$join); }else{ if(null != $conditions)$where = "WHERE ".$conditions; } if(is_array($order)){ $where .= ' ORDER BY '; $where .= implode(',', $order); }else{ if($order!=null)$where .= " ORDER BY ".$order; } if(!empty($limit))$where .= " LIMIT {$limit}"; $fields = empty($fields) ? "*" : $fields; $sql = "SELECT {$fields} FROM {$this->table} {$where}"; return $this->getData($sql); } // public function find($where=null,$order=null,$fields=null,$limit=1) { if( $record = $this->findAll($where, $order, $fields, 1) ){ return array_pop($record); }else{ return FALSE; } } // SQL public function query($sql){ $this->filter[] = $sql; $this->Statement = $this->pdo->query($sql); if ($this->Statement) { return $this; }else{ $msg = $this->pdo->errorInfo(); if($msg[2]) exit(' :' . $msg[2] . end($this->filter)); } } // SQL public function findSql($sql) { return $this->getData($sql); } // (conditions) public function delete($conditions) { $where = ""; if(is_array($conditions)){ $join = array(); foreach( $conditions as $key => $condition ){ $condition = '\''.$condition.'\''; $join[] = "{$key} = {$condition}"; } $where = "WHERE ( ".join(" AND ",$join). ")"; }else{ if(null != $conditions)$where = "WHERE ( ".$conditions. ")"; } $sql = "DELETE FROM {$this->table} {$where}"; return $this->pdo->exec($sql); } // public function add($row) { if(!is_array($row)){ return FALSE; } $row = $this->__prepera_format($row); if(empty($row)){ return FALSE; } foreach($row as $key => $value){ $cols[] = $key; $vals[] = '\''.$value.'\''; } $col = join(',', $cols); $val = join(',', $vals); $sql = "INSERT INTO {$this->table} ({$col}) VALUES ({$val})"; if( FALSE != $this->pdo->exec($sql) ){ if( $newinserid = $this->pdo->lastInsertId() ){ return $newinserid; }else{ $a=$this->find($row, "{$this->primary} DESC",$this->primary); return array_pop($a); } } return FALSE; } private function __prepera_format($rows) { $stmt = $this->pdo->prepare('DESC '.$this->table); $stmt->execute(); $columns = $stmt->fetchAll(PDO::FETCH_COLUMN); $newcol = array(); foreach( $columns as $col ){ $newcol[$col] = null; } return array_intersect_key($rows,$newcol); } }

インスタンス化クラス
 'localhost', //      
    'db_port' => 3306, //   mysql     
    'db_name' => 'test', //      
    'db_user' => 'root', //       
    'db_pass' => 'root', //      
    'db_prefix' => '', //    
];
 
//     
$db = new DB_API($config);
 
//   
$article = $db->set_table('article');
 
//     
$newdata = ['title'=>'this is a title'];
$r = $article->add($newdata);
if($r){
    echo '    !';
}else{
    echo '    !';
}

//     
$where = ['id'=>3];
$find = $article->find($where); //      
$find = $article->findAll($where); //       
print_r($find);
 
//     
$where = ['title'=>'hello world666'];
$update = $article->update(['id'=>1],$where);
if($update ){
    echo '    !';
    //      
    $newdata = $article->find('id=1');
    print_r($newdata);
}else{
    echo '    !';
}
 
//     
$where = ['id'=>1];
$del =  $article->delete($where);
if($del){
    echo '    !';
}else{
    echo '    !';
}
 
//           
$where = ['author'=>'TANKING'];
$count = $article->getCount($where);
echo $count;
 
//     SQL  
$sql = 'select * from article where id=3';
$lists = $article->findSql($sql);
print_r($lists);
 
//               
$where = ['id'=>1];
$res = $article->getField($where,'title');
if ($res) {
    echo $res;
}else{
    echo "    ";
}

//     
// $conditions    
// $order    
// $fields    
// $limit    
$res = $article->findAll($conditions=null,$order='id asc',$fields=null,$limit=null);
if ($res) {
    print_r($res);
}else{
    print_r("    ");
}

Author:TANKING