php PDO封装类实例

发布时间:2020-09-01编辑:脚本学堂
分享一个php pdo的封装类,对pdo基本函数做了简单封装,是学习php pdo用法的入门实例,需要的朋友参考下。

例子,php pdo封装类。

<?php
class DB {  
    private static $host = "localhost";
    private static $dbname = "bipp_new";
    private static $username = "root";
    private static $password = "123456";
    function __construct() {
        //$numargs = func_num_args();           
    }
    
    static function con(){
        return new PDO('mysql:host='.self::$host.';dbname='.self::$dbname, self::$username, self::$password,
        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    }
    
    /**
    /@parma $sql:SELECT name, colour, calories FROM fruit  WHERE calories <:calories and name =:name
    /@param $param_arr:array(":calories"=>123,":user"=>"user")
    **/
    static function query($sql,$param_arr){    
        $stmt = DB::con()->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));    
        $stmt->execute($param_arr);
        return $stmt->fetchAll();        
    } // www.jb200.com 脚本学堂
    
    /**
    /@parma $sql: insert into  `page` (pageName) values(:pageName)
    /@param $param_arr: array(":pageName"=>"new test name")
    **/
    static function exec($sql,$param_arr){        
        $stmt = DB::con()->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
        return $stmt->execute($param_arr);    
    }    
}
?>