溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在PHP中使用模型Model類封裝數(shù)據(jù)庫

發(fā)布時間:2021-05-31 16:26:03 來源:億速云 閱讀:112 作者:Leah 欄目:開發(fā)技術(shù)

怎么在PHP中使用模型Model類封裝數(shù)據(jù)庫?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

具體如下:

<?php
  //引入配置文件
  include "./config.php";
  class Model
  {
    public $link;//存儲連接對象
    public $tableName = "";//存儲表名
    public $field = "*";//存儲字段
    public $allFields = [];//存儲當(dāng)前表所有字段
    public $where = "";//存儲where條件
    public $order = "";//存儲order條件
    public $limit = "";//存儲limit條件
    /**
     * 構(gòu)造方法 初始化
     * @param string $tableName 要操作的表名
     */
    public function __construct($tableName)
    {
      //1.存儲操作的表名
      $this->tableName = PRE.$tableName;
      //2.初始化連接數(shù)據(jù)庫
      $this->getConnect();
      //3.獲得當(dāng)前表的所有字段
      $this->getFields();
    }
    /**
     * 初始化連接數(shù)據(jù)庫操作
     */
    public function getConnect()
    {
      //1.連接數(shù)據(jù)庫
      $this->link = mysqli_connect(HOST,USER,PWD,DB,PORT);
      //2.判斷連接
      if (mysqli_connect_errno($this->link)>0){
        echo mysqli_connect_error($this->link);
        exit;
      }
    }
    /**
     * 執(zhí)行并發(fā)送SQL(查詢)
     * @param string $sql 要查詢的SQL語句
     * @return array 返回查詢出來的二維數(shù)組
     */
    public function query($sql)
    {
      $result = mysqli_query($this->link,$sql);
      if ($result && mysqli_num_rows($result)>0) {
       $arr = [];
       while($row = mysqli_fetch_assoc($result)){
          $arr[] = $row;
       }
      }
    return $arr;
    }
    /**
     * 獲取當(dāng)前表的所有字段
     */
    public function getFields()
    {
      //查看表結(jié)構(gòu)
      $sql = "desc {$this->tableName}";
      //執(zhí)行并發(fā)送SQL
      $result = $this->query($sql);
      $fields = [];
      foreach ($result as $k => $v){
        $fields[] = $v['Field'];
      }
      $this->allFields = $fields;
    }
    /**
     * 執(zhí)行并發(fā)送SQL語句(增刪改)
     * @param string $sql 要執(zhí)行的SQL語句
     * @return bool|int|string 添加成功則返回上一次操作id,刪除修改操作則返回true,失敗則返回false
     */
    public function exec($sql)
    {
      $result = mysqli_query($this->link,$sql);
      //處理結(jié)果集
      if ($result && mysqli_affected_rows($this->link)>0){
        //判斷是否為添加操作,是則返回上一次執(zhí)行的id
        if (mysqli_insert_id($this->link)){
          return mysqli_insert_id($this->link);
        }
        //刪除修改操作成功則返回true
        return true;
      }else{
        //未執(zhí)行成功則返回false
        return false;
      }
    }
    /**
     * 查詢多條數(shù)據(jù)
     */
    public function select()
    {
      $sql = "select {$this->field} from {$this->tableName} {$this->where} {$this->order} {$this->limit}";
      //執(zhí)行并發(fā)送SQL
      return $this->query($sql);
    }
    /**
     * 查詢一條數(shù)據(jù)
     * @param string $id 要查詢的id
     * @return array 返回一條數(shù)據(jù)
     */
    public function find($id="")
    {
      //判斷id是否存在
      if (empty($id)){
        $where = $this->where;
      }else{
        $where = "where id={$id}";
      }
      $sql = "select {$this->field} from {$this->tableName} {$where} limit 1";
      //執(zhí)行并發(fā)送sql
      $result = $this->query($sql);
      //返回一條數(shù)據(jù)
      return $result[0];
    }
    /**
     * 設(shè)置要查詢的字段信息
     * @param string $field 要查詢的字段
     * @return object 返回自己,保證連貫操作
     */
    public function field($field)
    {
      //判斷字段是否存在
      if (empty($field)){
        return $this;
      }
      $this->field = $field;
      return $this;
    }
    /**
     * 統(tǒng)計總條數(shù)
     * @return int 返回總數(shù)
     */
    public function count()
    {
      //準(zhǔn)備SQL語句
      $sql = "select count(*) as total from {$this->tableName} limit 1";
      $result = $this->query($sql);
      //返回總數(shù)
      return $result[0]['total'];
    }
    /**
     * 添加操作
     * @param array $data 要添加的數(shù)組
     * @return bool|int|string 添加成功則返回上一次操作的id,失敗則返回false
     */
    public function add($data){
      //判斷是否是數(shù)組
      if (!is_array($data)){
        return $this;
      }
      //判斷是否全是非法字段
      if (empty($data)){
        die("非法數(shù)據(jù)");
      }
      //過濾非法字段
      foreach ($data as $k => $v){
        if (!in_array($k,$this->allFields)){
          unset($data[$k]);
        }
      }
      //將數(shù)組中的鍵取出
      $keys = array_keys($data);
      //將數(shù)組中取出的鍵轉(zhuǎn)為字符串拼接
      $key = implode(",",$keys);
      //將數(shù)組中的值轉(zhuǎn)化為字符串拼接
      $value = implode("','",$data);
      //準(zhǔn)備SQL語句
      $sql = "insert into {$this->tableName} ({$key}) values('{$value}')";
      //執(zhí)行并發(fā)送SQL
      return $this->exec($sql);
    }
    /**
     * 刪除操作
     * @param string $id 要刪除的id
     * @return bool 刪除成功則返回true,失敗則返回false
     */
    public function delete($id="")
    {
      //判斷id是否存在
      if (empty($id)){
        $where = $this->where;
      }else{
        $where = "where id={$id}";
      }
      $sql = "delete from {$this->tableName} {$where}";
      echo $sql;
      //執(zhí)行并發(fā)送
      return $this->exec($sql);
    }
    /**
     * 修改操作
     * @param array $data 要修改的數(shù)組
     * @return bool 修改成功返回true,失敗返回false
     */
    public function update($data){
      //判斷是否是數(shù)組
      if (!is_array($data)){
        return $this;
      }
      //判斷是否是全是非法字段
      if(empty($data)){
        die("非法數(shù)據(jù)");
      }
      $str = "";
      //過濾非法字段
      foreach ($data as $k => $v){
        if ($k == "id"){
          $where = "where id={$v}";
          unset($data[$k]);
        }
        if (in_array($k,$this->allFields)){
          $str .= "{$k}='{$v}',";
        }else{
          unset($data[$k]);
        }
      }
      //判斷是否有條件
      if (empty($this->where)){
        die("請輸入條件");
      }
      //去掉最右側(cè)的逗號
      $str = rtrim($str,",");
      $sql = "update {$this->tableName} set {$str} {$this->where}";
      return $this->exec($sql);
    }
    /**
     * where條件
     * @param string $where 輸入的where條件
     * @return $this 返回自己,保證連貫操作
     */
    public function where($where)
    {
      $this->where = "where ".$where;
      return $this;
    }
    /**
     * order排序條件
     * @param string $order 以此為基準(zhǔn)進(jìn)行排序
     * @return $this 返回自己,保證連貫操作
     */
    public function order($order)
    {
      $this->order = "order by ".$order;
      return $this;
    }
    /**
     * limit條件
     * @param string $limit 輸入的limit條件
     * @return $this 返回自己,保證連貫操作
     */
    public function limit($limit)
    {
      $this->limit = "limit ".$limit;
      return $this;
    }
    /**
     * 析構(gòu)方法
     * 關(guān)閉數(shù)據(jù)庫連接
     */
    public function __destruct()
    {
      mysqli_close($this->link);
    }
  }
 //自行調(diào)試
 $a = new Model("表名");
 // var_dump($a->find(3));
 // var_dump($a->select());
  // var_dump($a->count());
  // $res = $a->select();
  //var_dump($res);
?>

看完上述內(nèi)容,你們掌握怎么在PHP中使用模型Model類封裝數(shù)據(jù)庫的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI