数据库类的封装

简单的数据库类的封装

//连接数据库的类
class Newdb{
    public $host;//主机地址
    public $post = 3306;//mysql连接端口
    public $name;//数据库账号
    public $pwd;//数据库密码
    public $dbName;//数据库名
    public $charSet;//字符集
    public $link;//数据库连接对象
    public $res;//数据库返回的结果集
    
    //三私一共
    private  static $obj;//用来存Newdb对象
    
    //构造方法 实例化对象的时候自动调用
    private function __construct($config = array()){
        $this->host = $config["host"]?$config["host"] : "localhost";
        $this->name = $config["name"]?$config["name"] : "root";
        $this->pwd = $config["pwd"]?$config["pwd"] : "";
        $this->dbName = $config["dbName"]?$config["dbName"] : "mysql";
        $this->charSet = $config["charSet"]?$config["charSet"] : "utf8";
        
        //连接数据库
        $this->connectMysql();
        //设置字符集
        $this->setCharSet();
    }
    
    //私有化克隆方法
    private function __clone(){}
    //提供公共的返回对象方法
     static function getInstance($config = array()){
        if(!isset(self::$obj)){
            self::$obj = new self($config);    
        }
        return self::$obj;
    }
    
    
    //连接数据库
    function connectMysql(){
        $this->link = new MySQLi($this->host,$this->name,$this->pwd,$this->dbName);
        !mysqli_connect_error() or die("数据库连接失败");
        
    }
    //设置字符集
    function setCharSet(){
        $this->link->query("set names ".$this->charSet);
    }
    
    //执行sql语句返回结果集
    function queryN($sql){
        $this->res = $this->link->query($sql);
        if(!$this->res){
            echo ("<br />执行失败");
            echo "<br />失败的sql语句为:".$sql;
            echo "<br />出错的信息为:".mysql_error($this->link);
            echo "<br />错误代号为:".mysql_errno($this->link);
            die;
        }
        return $this->res;    
    }
    
    //返回字符串
    function getStr($sql){
        $zhi = $this->queryN($sql);
        $arr = $zhi->fetch_all();
        $brr = array();
        foreach($arr as $v){
            $brr[] = implode(",",$v);
        }
        return implode("^",$brr);
    }
    //返回json
    function getJson($sql){
        $zhi = $this->queryN($sql);
        while($row = $zhi->fetch_assoc()){
            $brr[] = $row;
        }
        return json_encode($brr);
    }
    //返回关联数组
        function getAssoc($sql){
        $zhi = $this->queryN($sql);
        while($row = $zhi->fetch_assoc()){
            $brr[] = $row;
        }
        return $brr;
    }
    //返回索引数组
    function getAttr($sql){
        $zhi = $this->queryN($sql);
        return $zhi->fetch_all();
    }
}

posted @ 2018-10-10 09:20  Prinlily  阅读(380)  评论(0编辑  收藏  举报