封装mysqli

本文介绍了一个使用PHP封装的MySQLi类,通过单例模式实现数据库连接的管理和操作,包括连接、查询、增删改查等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
header('content-type:text/html;charset=utf-8');
/**
 * content 封装一个单例的mysqli类
 *
 * 单例模式:三私一公
 * 1.私有的构造方法:防止类外实例
 * 2.私有的克隆方法:防止克隆
 * 3.私有的静态属性:保存类的实例
 * 4.公共的静态方法:获取类的实例
 */
class mysqlis{
    //私有属性
    private static $dbcon=false;
    private $host;//ip
    private $port;//端口号
    private $user;//用户
    private $pwd;//密码
    private $db;//数据库
    private $charset;//字符集
    private $link;//链接
    public $table;//表名
    public $where;//条件
    public $fields='*';//查询所有
    public $orderBy;//排序
    //私有的构造方法
    private function __construct($config=array()){
        $this->host=$config['host']?$config['host']:'127.0.0.1';//ip
        $this->port=$config['port']?$config['port']:'3306';//端口号
        $this->user=$config['user']?$config['user']:'root';//用户
        $this->pwd=$config['pwd']?$config['pwd']:'root';//密码
        $this->db=$config['db']?$config['db']:'mysqli';//数据库
        $this->charset=$config['charset']?$config['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->pwd);
        // var_dump($this->link);die;
        if (!$this->link) {
            echo "数据库连接失败";
            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('不可以克隆哟');
    }
    //公共的静态方法
    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 table($table=''){
         if (!empty($table)) {
            $this->table=$table;
        }
        return $this;
    }
    public function fields($fields='*'){
        $this->fields=$fields;
        return $this;
    }
    //where条件
    public function where($where) {
       if (is_array($where)) {
              foreach ($where as $key => $value) {
                     if ($this->where != '') {
                            $this->where .= ' and ';
                     }
                     $this->where .= $key . '='.$value;
              }
       }else{
            if ($this->where != '') {
                $this->where .= ' and ';
            }
            $this->where .= $where;
       }
       // echo $this->where;die;
       return $this;
    }
  //查询一条数据
    public function findOne(){
        if (!empty($this->where)) {
            $sql='select ' . $this->fields . ' from ' . $this->table . ' where ' . $this->where;
        }
        else{
            $sql='select ' . $this->fields . ' from ' . $this->table;
        }
        echo $sql;
        // return $this->link->query($sql)->fetch_array(MYSQLI_ASSOC);
    }
    //order by      
    public function orderBy($str, $sxu) {
        $this->order = 'order by ' . $str . ' ' . $sxu;
        return $this;
    }
    //获得最后一条记录id
    public function getInsertid(){
        return mysqli_insert_id($this->link);
    }
    //封装添加数据的方法$table 表名;$data 添加的数据
    public function insert($table,$data){
        //遍历数组,得到每一个字段和字段的值
        $key_str='';
        $val_str='';
        foreach ($data as $key => $val) {
            if (empty($val)) {
                die('出错啦');
            }
            //$key的值是每一个字段s一个字段所对应的值
            $key_str=$key.',';
            $val_str="'$val',";
        }
        $key_str=trim($key_str,',');
        $val_str=trim($val_str,',');
        //判断添加的数据是否为空
        $sql="insert into $table ($key_str) values ($val_str)";
        $this->query($sql);
        //返回上一次增加操做产生ID值
        return $this->getInsertid();
    }
    //封装删除一条数据的方法$table 表名;$where 条件
    public function delOne($table,$where){
        if (is_array($where)) {
            foreach ($where as $key => $value) {
                $dels = $key.'='.$value;
            }           
        }else{
            $dels=$where;
        }
        //删除的sql语句
        $sql="delete from $table where $dels";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }
    //封装一个可以删除多条数据的方法$table 表名;$where 条件
    public function delAll($table,$where){
        if (is_array($where)) {
            foreach ($where as $key => $value) {
                if (is_array($value)) {
                    $dels=$key.'in('.implode(',',$value).')';
                }else{
                    $dels = $key.'='.$value;
                }                
            }
        }else{
            $dels=$where;
        }
        //删除的sql语句
        $sql="delete from $table where $dels";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
    }
    /**
    * 修改操作
    * $table 表名
    * $data 要修改的数据
    * $where 条件
    */
    public function update($table,$data,$where){
           //遍历数组,得到每一个字段和字段的值
        $res='';
        foreach ($data as $key => $value) {
            $res.="$key='$value',";
        }
        $res=trim($res,',');
        //修改的sql语句
        $sql="update $table set $res where $where";
        $this->query($sql);
        //返回受影响的行数
        return mysqli_affected_rows($this->link);
   }
    
}

$mysqli_obj=mysqlis::getIntance();
var_dump($mysqli_obj);die;
//查看表数据
// $sql=$mysqli_obj->table('user')->findOne();
// $sql=$mysqli_obj->table('user')->where(['user'=>'班长'])->where('u_id=4') ->findOne();

//执行添加
// $list=$mysqli_obj->insert("user",array('user'=>'学委'));
// print_R($sql);
// 删除语句
// $del=$mysqli_obj->delOne("user","u_id=14");
// $del=$mysqli_obj->delAll("user","u_id in(13,15)");
// 修改语句
// $up=$mysqli_obj->update("user",array('user'=>'二哈'),"u_id=16");
// print_R($up);
 ?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值