PHP使用mysqli擴展庫實現增刪改查(面向對象版)

mysqli擴展庫mysql擴展庫的改進版本,在mysql擴展庫的基礎上提升了穩定性和效率,mysqli擴展庫有兩套東西,一套就是面向過程的mysqli另外一套是面向對象的mysqli。操做方式大致和mysql擴展庫大致一致,此次仍是先抽取出來一個操做mysql的工具類,和調用的類。php

1.mysqli擴展庫操做數據庫工具類html

<?php
 //數據庫操做類
  class DBUtil{
   private $host="localhost";
   private $username="root";
   private $password="123456";
   private $dbname="student";
   private $conn;
   public function DBUtil(){
     $this->conn=new mysqli($this->host, $this->username, $this->password,$this->dbname) or die($this->conn->connect_error);
    
   }
  //查詢
   public function query($sql){
     $all= $this->conn->query($sql);
     return $all;
   }
  //插入,修改,刪除
   public function otherOperate($sql){
      if($this->conn->query($sql)){
        if($this->conn->affected_rows>0){
           return "OK";
        }else{
           return "ERROOR";
        }
      }
   }
   public function close(){
     $this->conn->close();
   }
  }
?>

2.下面是具體的調用工具類的代碼mysql

<?php
  require_once "MySQLUtil.php";
   /*$sql="select * from m_student";
   $util=new DBUtil();
   $result=$util->query($sql);
   while($row=$result->fetch_assoc()){
        echo "$row[stuName]"."</br>";
   }
   $result->free();
   $util->close();*/
   $sql="update m_student set stuName='楊冪' where id=3";
   $util=new DBUtil();
   $result=$util->otherOperate($sql);
   echo $result;
   $util->close();
?>

參考閱讀:www.manongjc.com/article/1206.htmlsql

相關文章
相關標籤/搜索