對象static private $_instance;//本類執行個體//建構函式初始化$mysqli對象private function __construct() {$this->mysqli=new mysqli($this->host,$this->user,$this->pwd,$this->db,$this->port);if(mysqli_connect_errno()){$this->mysqli=false;echo mysqli_connect_error();die();}else{$this->mysqli->set_charset($char);}}//解構函式:釋放結果集和關閉資料庫public function __destruct(){$this->free();$this->close();}//初始化$mysqli對象public static function getInstance(){if(!(self::$_instance instanceof self)) {self::$_instance = new self();}return self::$_instance;}//釋放結果集private function free(){@$this->result->free();}//關閉資料庫連接private function close(){$this->mysqli->close();}//執行sql語句public function query($sql){return $this->mysqli->query($sql);}//擷取查詢結果public function get_result_array($table,$field,$c$table=$this->prefix.$table;if(is_array($field)){$field = join(',',$field);}$sql = "SELECT $field FROM ".$table;if(!empty($condition))$sql .=" $condition ";$this->result = $this->query($sql);$return = array();while($row = $this->fetch($this->result)){$return[] = $row;}$this->free();return $return;}//增刪改操作public function execute($table,$action,$arr_field=array(),$c$table=$this->prefix.$table;switch($action){case 'INSERT':$str_field = '';$str_val = '';foreach($arr_field as $key=>$val){$str_field .= '`'.$key.'`,';$str_val .= '\''.$val.'\',';}$str_field = rtrim($str_field, ',');$str_val = rtrim($str_val, ',');$sql = "INSERT INTO $table ($str_field) VALUES ($str_val) ";break;case 'DELETE':$sql = "DELETE FROM $table";if (!empty($condition)) $sql .= " WHERE $condition";break;case 'UPDATE':$str_field = '';foreach($arr_field as $key => $val){$str_field.= '`'.$key ."` ='$val',";}$str_field = rtrim($str_field, ',');$sql = "UPDATE $table SET $str_field";if (!empty($condition)) $sql .= " WHERE $condition";break;}$this->query($sql);return $this->get_affected_rows();}//獲得受影響行數(針對增刪改操作)public function get_affected_rows(){return $this->mysqli->affected_rows;}//擷取集合條數public function get_rows($table,$c 1 ',$id='id'){$table=$this->prefix.$table;$sql="SELECT COUNT($id) num FROM ".$table." $condition";$this->result=$this->query($sql);$row=$this->fetch($this->result);return $row['num'];}//獲得結果集public function fetch($result){return $result->fetch_array($this->fetch_mode);}//獲得所有結果集public function fetch_all($result){$rows=array();while($row=$this->fetch($result)){$rows[]=$row;}return $rows;}}
想用PHP寫手機App的介面封裝的一個資料庫操作類
以上就介紹了PHP mysqli資料庫操作類,包括了對象方面的內容,希望對PHP教程有興趣的朋友有所協助。