您好,登錄后才能下訂單哦!
這篇文章給大家介紹使用PHP怎么封裝一個mysqli數據庫操作類,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
<?php class db_class{ public $db_url; //連接地址 public $db_username; //連接名 public $db_userpassword; //連接密碼 public $db_name; //數據庫名 public $db_tablename; //表名 public $db_conn; //數據庫連接 public $db_order; public $db_limit; public function db_getconn(){ //連接數據庫 $this->db_conn= mysqli_connect($this->db_url,$this->db_username,$this->db_userpassword,$this->db_name); if (!$this->db_conn) { echo "連接 MySQL 失敗: " . mysqli_connect_error(); } } public function __construct($db_url,$db_username,$db_userpassword,$db_name){ //構造方法賦值 $this->db_url=$db_url; $this->db_username=$db_username; $this->db_userpassword=$db_userpassword; $this->db_name=$db_name; $this->db_order=""; $this->db_limit=""; $this->db_getconn(); mysqli_query($this->db_conn,'set names utf8'); } public function db_settablename($db_tablename){ //設置表名 $this->db_tablename=$db_tablename; } public function db_setorder($str){ //排序操作 $this->db_order="order by $str"; } public function db_setlimit($start,$end){ //分頁操作 $this->db_limit="limit $start,$end"; } public function db_select($typearr="",$where=""){ //查詢操作 if(empty($typearr)){ $typearr="*"; } else{ $typearr=implode(",",$typearr); } if(empty($where)){ $where=""; }else{ $where="where ".$where; } $arr=array(); $sql="select $typearr from $this->db_tablename $where $this->db_order $this->db_limit "; $result = mysqli_query($this->db_conn,$sql); while($row = $result->fetch_array()) { $arr[]=$row; } return $arr; } public function db_update($typearr,$valuearr,$where=""){ //更新操作 $sql=""; if(empty($where)){ $where=""; }else{ $where=" where ".$where; } $sql.="update $this->db_tablename set "; foreach ($typearr as $key=>$value){ if(count($typearr)-1==$key){ $sql.=$value."='".$valuearr[$key]."'"; }else{ $sql.=$value."='".$valuearr[$key]."'".","; } } $sql.=$where; mysqli_query($this->db_conn,$sql); } public function db_delete($typestr,$valuestr){ //刪除操作 $sql="delete from $this->db_tablename WHERE $typestr=$valuestr"; mysqli_query($this->db_conn,$sql); } public function db_insert($typearr,$valuearr){ //插入操作 $sql="insert into $this->db_tablename(".implode(",", $typearr).") values(".implode(",", $valuearr).")"; mysqli_query($this->db_conn,$sql); } public function __destruct(){ //析構方法關閉連接 mysqli_close($this->db_conn); } }
關于使用PHP怎么封裝一個mysqli數據庫操作類就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。