<?php

//header
header('content-type:text/html;charset=UTF-8');

class DB {
    //定义属性
    private $host;//主机名
    private $port;//端口号
    private $name;//用户名
    private $pass;//密码
    private $dbname;//数据库名
    private $charset;//设置字符集
    private $link;//连接数据库
    private static $instance;
    //初始化  构造函数
    private function __construct($arr = array()){
        $this->host = isset($arr['host']) ? $arr['host'] : 'localhost' ;
        $this->port = isset($arr['port']) ? $arr['port'] : '3306' ;
        $this->name = isset($arr['name']) ? $arr['name'] : 'root' ;
        $this->pass = isset($arr['pass']) ? $arr['pass'] : 'root' ;
        $this->dbname = isset($arr['dbname']) ? $arr['dbname'] : 'yii2_project' ;
        $this->charset = isset($arr['charset']) ? $arr['charset'] : 'utf8' ;
        //连接数据库
        $this->db_connect();
        //选择数据库
        $this->db_usedb();
        //设置字符集
        $this->db_charset();
    }
    //连接数据库
    private function db_connect(){
        //主机名:端口号   用户名  密码
        $this->link = mysqli_connect($this->host.':'.$this->port, $this->name, $this->pass);
        //连接失败
        if(!$this->link){
            echo '数据库连接失败<br>';
            echo '错误编码是:'.mysqli_errno($this->link).'<br>';
            echo '错误信息是:'.mysqli_error($this->link).'<br>';
            exit;
        }
    }
    //选择数据库
    private function db_usedb(){
        mysqli_query($this->link, "use {$this->dbname}");
    }
    //设置字符集
    private function db_charset(){
        mysqli_query($this->link, "set names {$this->charset}");
    }
    //私有化克隆函数,防止外界克隆对象
    private function __clone()
    {
    }
 
    //单例访问统一入口
    public static function getInstance($arr)
    {
        if(!(self::$instance instanceof self))
        {
            self::$instance = new self($arr);
        }
        return self::$instance;
    }    
    /**
     * 执行语句
     * @param  $sql
     * @return source
     */
    private function query($sql){
        $res = mysqli_query($this->link, $sql);
        if(!$res){
            echo 'sql语句有错误<br>';
            echo '错误编码是:'.mysqli_errno($this->link).'<br>';
            echo '错误信息是:'.mysqli_error($this->link).'<br>';
            exit;
        }
        return $res;//成功返回数据
    }
    /**
     * 获取刚插入数据的id
     * @return int
     */
    public function getInsertId(){
        return mysqli_insert_id($this->link);
    }
    /**
     * 查询某个字段, 例如 select count(*),  select username
     * @param  $sql
     * @return string or int
     */
    public function getOne($sql){
        $query = $this->query($sql);
        return mysqli_free_result($query);
    }
    /**
     * 获取一行记录
     * @param  $sql
     * @return array 一维
     */
    public function getRow($sql, $type='assoc'){
        $query = $this->query($sql);
        if(!in_array($type, array("assoc", "array", "row"))){
            die("mysql_query error");
        }
        $functionname = "mysqli_fetch_".$type;
        return $functionname($query);
    }
    /**
     * 前置条件:通过资源获取一条记录
     * @param  $query source
     * @return array 一维
     */
    public function getRowFromSource($query, $type="assoc"){
        if(!in_array($type, array("assoc", "array", "row"))){
            die("mysql_query error");
        }
        $functionname = "mysqli_fetch_".$type;
        return $functionname($query);
    }
    /**
     * 获取所有记录
     * @param  $sql
     * @return array 二维
     */
    public function getAll($sql){
        $query = $this->query($sql);
        $list = array();
        while ($row = $this->getRowFromSource($query)) {
            $list[] = $row;
        }
        return $list;
    }
    /*
    * 新增数据方法
    * @param1 $table, $data 表名 数据
    * @return 上一次增加操做产生ID值
    */
    public function insert($table, $data){
        //遍历数组,得到每一个字段和字段的值
        $kstr = '' ;
        $vstr = '' ;
        foreach ($data as $key => $val) {
            //$key是字段名, $val是对应的值
            $kstr .= $key."," ;
            $vstr .= "'$val',";
        }
        $kstr = rtrim($kstr, ',');
        $vstr = rtrim($vstr, ',');
        //添加的sql语句
        $sql = "insert into $table ($kstr) values ($vstr)";
        
        //执行
        $this->query($sql);
        //返回上一次增加操做产生ID值
        return $this->getInsertId();
    }
    /*
    * 删除一条数据方法
    * @param1 $table, $where=array('id'=>'1') 表名 条件
    * @return 受影响的行数
    */
    public function deleteOne($table, $where){
        if(is_array($where)){
            foreach ($where as $key => $val) {
                $condition = $key.'='.$val;
            }
        } else {
            $condition = $where;
        }
        $sql = "delete from $table where $condition";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }
    /*
    * 删除多条数据方法
    * @param1 $table, $where 表名 条件
    * @return 受影响的行数
    */
    public function deleteAll($table, $where){
        if(is_array($where)){
            foreach ($where as $key => $val) {
                if(is_array($val)){
                    $condition = $key.' in ('.implode(',', $val) .')';
                } else {
                    $condition = $key. '=' .$val;
                }
            }
        } else {
            $condition = $where;
        }
        $sql = "delete from $table where $condition";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }
    /*
    * 修改数据方法
    * @param1 $table,$data,$where 表名 数据 条件
    * @return 受影响的行数
    */
    public function update($table,$data,$where){
        //遍历数组,得到每一个字段和字段的值
        $str='';
        if(is_array($data)){
            foreach($data as $key=>$v){
                $str.="$key='$v',";  
            }
            $str=rtrim($str,',');
            //修改的SQL语句
            $sql="update $table set $str where $where";
        } else {
            //修改的SQL语句
            $sql="update $table set $data where $where";
        }
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }

最新文章

  1. #ifndef 的用法
  2. Problem 2136 取糖果---FUOJ (线段树+维护)
  3. 【Software Clone】2014-IEEE-Towards a Big Data Curated Benchmark of Inter-Project Code Clones
  4. VC中常用的宏
  5. Python--关于 join 和 split
  6. git命令学习用
  7. Python:列表,元组
  8. bzoj1832: [AHOI2008]聚会
  9. Ubuntu 字体安装
  10. github继续折腾
  11. mysql源码分析
  12. Python3 官方文档翻译 - 5 数据结构
  13. 深刻理解反射(Reflection)
  14. 《大型网站技术架构:核心原理与案例分析》【PDF】下载
  15. SVM-sklearn
  16. vuejs2+webpack2+vuxui2多页面架手脚,支持二级目录
  17. 转:The Difference Between a LayoutTransform and a RenderTransform
  18. ABAP知识点笔记
  19. 类的 __call__ 和__repr__ 方法
  20. arm学习之汇编跳转指令总结

热门文章

  1. Python常用内置函数总结
  2. Mybatis + Mysql 插入数据时中文乱码问题
  3. 微信内嵌浏览器sessionid丢失问题,nginx ip_hash将所有请求转发到一台机器
  4. Centos screen远程会话管理命令
  5. 关于MySql has gone away问题的解决
  6. 关于easyui遇到的一些问题
  7. Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined) C. Ray Tracing
  8. Excel函数汇总:
  9. innoDB 存储引擎
  10. function,new function,Function,new Function 之间的区别