7.16 基本数据库类

<?php
    class Db{
        private $host;
        private $username;
        private $password;
        private $database;
        private $conn;
        public function __construct($host,$username,$password,$database,$charset='utf-8'){
            $this->host = $host;
            $this->username = $username;
            $this->password = $password;
            $this->database = $database;
            $this->conn = new mysqli($this->host,$this->username,$this->password,$this->database);
            mysqli_query($this->conn,"set names ".$charset);
        }
        //执行增删改的方法
        public function query($sql){
            return $result = $this->conn->query($sql);            
        }
        //查询并返回索引数组
        public function getDdAttr($sql){
            $result = $this->conn->query($sql);
            return $attr = $result->fetch_all();            
        }
        //查询并返回json数据
        public function getJson($sql){
            $result = $this->conn->query($sql);
            $attr = $result->fetch_all();
            return json_encode($attr);            
        }
        //查询并返回关联数组
        public function getAssocAttr($sql){
            $result = $this->conn->query($sql);
            $newAttr = array();
            while($attr = $result->fetch_assoc()){
                $newAttr[] = $attr;
            }
            return $newAttr;            
        }
        //查询并返回字符串
        public function getStr($sql){
            $result = $this->conn->query($sql);
            $attr = $result->fetch_all();    
            $str = "";
            foreach($attr as $v){
                $str .=join(chr(1),$v);
                $str .= chr(2); 
            }
            return substr($str,0,strlen($str)-1);    
        }
        
    }
?>

猜你喜欢

转载自www.cnblogs.com/sunhao1987/p/9401142.html