封装mysqli类
类:
<?php
header('content-type:text/html;charset=utf-8');
/*
掌握满足单例模式的必要条件
(1)私有的构造方法-为了防止在类外使用new关键字实例化对象
(2)私有的成员属性-为了防止在类外引入这个存放对象的属性
(3)私有的克隆方法-为了防止在类外通过clone成生另一个对象
(4)公有的静态方法-为了让用户进行实例化对象的操作
*/
class ConnectMysqli{
   //私有的属性
   private static $dbcon=false;
   private $host;
   private $port;
   private $user;
   private $pass;
   private $db;
   private $charset;
   private $link;
    //私有的构造方法
    private function  __construct($config=array()){
        $this->host = $config['host'] ? $config['host'] : 'localhost';
        $this->port = $config['port'] ? $config['port'] : '3306';
        $this->user = $config['user'] ? $config['user'] : 'root';
        $this->pass = $config['pass'] ? $config['pass'] : 'root';
        $this->db = $config['db'] ? $config['db'] : 'small2';
        $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->user,$this->pass);
        if(!$this->link){
            echo "数据库连接失败<br>";
            echo "错误编码".mysqli_errno($this->link)."<br>";
            echo "错误信息".mysqli_error($this->link)."<br>";
            exit;
        }
      }
      //设置字符集
       private function db_charset(){
          mysqli_query($this->link,"set names {$this->charset}");
       }
       //选择数据库
      private function db_usedb(){
         mysqli_query($this->link,"use {$this->db}");
      }
//私有的克隆
      private function __clone(){
          die('clone is not allowed');
      }
//公用的静态方法
     public static function getIntance(){
          if(self::$dbcon==false){
            self::$dbcon=new self;
          }
          return self::$dbcon;
      }
      
      //执行sql语句的方法
       public 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>";
         }
         return $res;
      }
      //打印数据
       public function p($arr){
           echo "<pre>";
           print_r($arr);
           echo "</pre>";
       }
       public function v($arr){
        echo "<pre>";
           var_dump($arr);
           echo "</pre>";
       }
//获得最后一条记录id
       public function getInsertid(){
         return mysqli_insert_id($this->link);
       }
/**
        * 查询某个字段
        * @param  
        * @return string or int
        */
       public function getOne($sql){
         $query=$this->query($sql);
           return mysqli_free_result($query);
       }
       //获取一行记录,return array 一维数组
       public function getRow($sql,$type="assoc"){
         $query=$this->query($sql);
         if(!in_array($type,array("assoc",'array',"row"))){
              die("mysqli_query error");
         }
         $funcname="mysqli_fetch_".$type;
         return $funcname($query);
       }
       //获取一条记录,前置条件通过资源获取一条记录
       public function getFormSource($query,$type="assoc"){
        if(!in_array($type,array("assoc","array","row")))
        {
           die("mysqli_query error");
        }
        $funcname="mysqli_fetch_".$type;
        return $funcname($query);
       }
       //获取多条数据,二维数组
       public function getAll($sql){
         $query=$this->query($sql);
         $list=array();
         while ($r=$this->getFormSource($query)) {
           $list[]=$r;
         }
         return $list;
       }
/**
          * 定义添加数据的方法
          * @param string $table 表名
          * @param string orarray $data [数据]
          * @return  int 最新添加的id
          */
         public function insert($table,$data){
          //遍历数组,得到每一个字段和字段的值
          $key_str='';
          $v_str='';
          
          foreach($data as $key=>$v){
            if(empty($v)){
             die("error");
          }
               //$key的值是每一个字段s一个字段所对应的值
                $key_str.=$key.',';
                $v_str.="'$v',";
          }
          $key_str=trim($key_str,',');
          $v_str=trim($v_str,',');
//判断数据是否为空
          
          $sql="insert into $table ($key_str) values ($v_str)";
          $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);
        }
      /**
       * [修改操作description]
       * @param  [type] $table [表名]
       * @param  [type] $data  [数据]
       * @param  [type] $where [条件]
       * @return [type]     
       */
      public function update($table,$data,$where){
         //遍历数组,得到每一个字段和字段的值
         $str='';
        foreach($data as $key=>$v){
          $str.="$key='$v',";  
        }
        $str=rtrim($str,',');
        //修改SQL语句
        $sql="update $table set $str where $where";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
      }
}
?>
测试:
//mysqli测试
$db=ConnectMysqli::getIntance();
//var_dump($db);
/*$sql="select * from acticle";
$list=$db->getAll($sql);
$db->p($list);*/
/*$sql="select * from acticle where acticle_id=95";
$list=$db->getRow($sql);
$db->p($list);
*/
/*$sql="select title from acticle";
$list=$db->getOne($sql);
$db->p($list);不行*/
//$list=$db->insert("users",$_POST);
//$del=$db->deleteOne("users","id=29");
//$del=$db->deleteAll("users","id in(27,28)");
//$up=$db->update("users",$_POST,"id=27");
//print_R($list);
封装mysqli类的更多相关文章
- php封装的mysqli类完整实例
		本文实例讲述了php封装的mysqli类.分享给大家供大家参考,具体如下:类: <?php header('content-type:text/html;charset=utf-8'); /* ... 
- PHP连接数据库:封装成类
		php连接数据库,操作他增删改查等操作,其中要多次连接数据库,每个页面也需要连接数据库,更改数据会及其麻烦: 为了便于数据库的更改,我们可以把固定的那几句话封装成类,这样虽然代码量也差不多,但是有利于 ... 
- PDO 增删改查封装的类
		Selecting Data 你在mysql_*中是这样做的 <?php $result = mysql_query('SELECT * from table') or die(mysql_er ... 
- SpringMVC 自动封装枚举类的方法
		springmvc默认无法自动封装枚举类,解决方法如下: 1.枚举类 public enum GoodsPromoteEnum { /** * 0 精品 */ fine("精品", ... 
- iOS NSURLSession 封装下载类
		周六日鼓捣NSURLSession,效率虽然低下,最后还是有了一点点眉目.昨天和汤老师一起测试,又对它加深了一点理解.趁热打铁,先总结一下. 封装的类,对外用的方法,我写的是类方法,所以,在类方法中, ... 
- 封装application类
		<?php //判断用户是否是通过入口文件访问 if(!defined('ACCESS')){ echo '非法请求'; die; } //封装初始化类 cla ... 
- 封装mysql类
		类: <?phpheader("content-type:text/html;charset=utf-8");//封装一个类/*掌握满足单例模式的必要条件(1)私有的构造方法 ... 
- yii2封装一个类控制div宽度,高度
		1.首先,封装一个类,放在文件夹vendor下,命名为articls.php. <?phpclass Articles{ //测试 function add() { r ... 
- 封装DB类
		封装DB类 一般一个类单独书写在一个Php文件中,为了见名知意,会对文件名有一个规范:类名.class.php 第1步: 创建DB类 第2 步: 属性设计 第3步: 初 ... 
随机推荐
- php 请求参数限制
			公司有个群发短信的小项目,项目上线了很久也没有什么问题,最近有商家说 我短信群发不能用 现象是:发现有时候可以发送,有时候不可以发送,看截图发送的手机数量不一样 通过调试php代码发现 php 只接受 ... 
- uploadify
			uploadify 返回值(回调函数)总结: 最近使用开发一个图片上传模块的时候使用了一个jq插件--uploadify,但是下面就是让人很苦逼的一个下午……一直调试不好,无法接收返回值.google ... 
- nsenter  into docker. selinux(semanage,restorecon)
			Docker容器运行后,如何进入容器进行操作呢?起初我是用SSH.如果只启动一个容器,用SSH还能应付,只需要将容器的22端口映射到本机的一个端口即可.当我启动了五个容器后,每个容器默认是没有配置SS ... 
- Win7下VS2008编译QtiPlot
			Win7下VS2008编译QtiPlot By wangsh 2011-11-25 QtiPlot 是一款开源免费的科学绘图软件,可运行在多个平台(windows.Linux等)中,从功能上讲,Qti ... 
- SQL SERVER中非聚集索引的覆盖,连接,交叉,过滤
			1.覆盖索引:select和where中包含的结果集中应存在“非聚集索引列”,这样就不用查找基表了,索引表即可搞定: 2.索引交叉:索引的交叉可以理解成建立多个非聚集索引之间的join,如表实体一 ... 
- LightOj1366 - Pair of Touching Circles(求矩形内圆的对数)
			题目链接:http://lightoj.com/volume_showproblem.php?problem=1366 题意:一个H*W的矩形,现在要放入两个外切的圆,问能放多少对这样的圆,其中圆心和 ... 
- windows 访问 ubuntu虚拟机 django服务器 失败
			配置ubuntu配置成桥接,在ubuntu虚拟机中运行django.py开发服务器.windows访问django失败. 虚拟机运行: python manage.py runserver 0.0.0 ... 
- python 递归
			学习python,正好用一个例子练习一下递归. 参考文档: http://www.runoob.com/python/python-exercise-example18.html 题目:求s=a+aa ... 
- C# serialport
			最近使用C#写串口的程序,实现串口助手的功能,参考文档记录于此. 参考文档 http://blog.csdn.net/geekwangminli/article/details/7851673 htt ... 
- Task+http请求
			Task+http请求 这个算是一个简单的事例吧 
