MySQL資料庫操作類(PHP實現,支援連貫操作)
阿新 • • 發佈:2018-12-24
<?php
/**
* Author: helen
* CreateTime: 2016/4/12 20:14
* description: 資料庫操作類(僅對接MySQL資料庫,主要利用MySQLi函式)
*/
class Database{
//MySQL主機地址
private $_host;
//MySQL使用者名稱
private $_user;
//MySQL使用者密碼
private $_password;
//指定資料庫名稱
private $_database;
//MySQL資料庫埠號
private $_port ;
private $_socket;
//當前資料庫物件
private $_dbObj;
//資料庫表
private $_table;
//資料庫表物件
private $_tableObj;
// 最近錯誤資訊
protected $error = '';
// 資料資訊
protected $data = array();
// 查詢表示式引數
protected $options = array();
protected $_validate = array(); // 自動驗證定義
protected $_auto = array(); // 自動完成定義
protected $_map = array(); // 欄位對映定義
protected $_scope = array(); // 命名範圍定義
// 鏈操作方法列表
protected $methods = array('strict','order','alias','having','group','lock' ,'distinct','auto','filter','validate','result','token','index','force');
/**
* Database類初始化函式
* 取得DB類的例項物件 欄位檢查
* @access public
* @param string $host MySQL資料庫主機名
* @param string $user MySQL資料庫使用者名稱
* @param string $password MySQL資料庫密碼
* @param string $database 指定操作的資料庫
* @return mixed 資料庫連線資訊、錯誤資訊
*/
public function __construct($host,$user,$passowrd,$database,$port=3306){
$this->_initialize();
if(!isset($host)||!isset($user)||!isset($passowrd)||!isset($database)){
return false;
}else{
$this->_host = $host;
$this->_user = $user;
$this->_password = $passowrd;
$this->_database = $database;
$this->_port = $port;
$_dbObj = new mysqli($host,$user,$passowrd,$database,$port);
if($_dbObj->connect_errno){
$this->error = $_dbObj->connect_error;
return false;
}else{
$this->_dbObj = $_dbObj;
return $this;
}
}
}
/**
* 錯誤資訊函式
* 返回資料庫操作過程中最後一次執行時的錯誤資訊
* @access public
* @return mixed 資料庫連線錯誤資訊(正常返回'')
*/
public function error(){
return $this->error;
}
// 回撥方法 初始化模型
protected function _initialize() {}
/**
* 設定資料物件的值
* @access public
* @param string $name 名稱
* @param mixed $value 值
* @return void
*/
public function __set($name,$value) {
// 設定資料物件屬性
$this->data[$name] = $value;
}
/**
* 獲取資料物件的值
* @access public
* @param string $name 名稱
* @return mixed
*/
public function __get($name) {
return isset($this->data[$name])?$this->data[$name]:null;
}
/**
* 檢測資料物件的值
* @access public
* @param string $name 名稱
* @return boolean
*/
public function __isset($name) {
return isset($this->data[$name]);
}
/**
* 銷燬資料物件的值
* @access public
* @param string $name 名稱
* @return void
*/
public function __unset($name) {
unset($this->data[$name]);
}
/**
* 利用__call方法實現一些特殊的方法(對於呼叫類中不存在方法的解決方案)
* @access public
* @param string $method 方法名稱
* @param array $args 呼叫引數
* @return mixed
*/
public function __call($method,$args) {
/*if(in_array(strtolower($method),$this->methods,true)) {
// 連貫操作的實現
$this->options[strtolower($method)] = $args[0];
return $this;
}elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
// 統計查詢的實現
$field = isset($args[0])?$args[0]:'*';
return ;
}elseif(strtolower(substr($method,0,5))=='getby') {
// 根據某個欄位獲取記錄
$field = parse_name(substr($method,5));
$where[$field] = $args[0];
return ;
}elseif(strtolower(substr($method,0,10))=='getfieldby') {
// 根據某個欄位獲取記錄的某個值
$name = parse_name(substr($method,10));
$where[$name] =$args[0];
return ;
}elseif(isset($this->_scope[$method])){// 命名範圍的單獨呼叫支援
return ;
}else{
}*/
}
/*
* 選擇資料庫
* @access public
* @param string $database 選擇的資料庫名稱
* @return mixed 資料庫連線資訊
* */
public function select_db($database){
$select_db = mysqli_select_db($this->_dbObj,$database);
if($select_db){
$this->_database = $database;
$_dbObj = new mysqli($this->_host,$this->_user,$this->_password,$database,$this->_port);
$this->_dbObj = $_dbObj;
return $this;
}else{
$this->error = mysqli_error($this->_dbObj);
return false;
}
}
/*
* 資料庫使用者更換
* @access public
* @param string $user 資料庫使用者名稱稱
* @param string $password 資料庫使用者密碼
* @return mixed 資料庫連線資訊
* */
public function change_user($user,$password){
$change_user = mysqli_change_user($this->_dbObj,$user,$password,$this->_database);
if($change_user){
$this->_user = $user;
$this->_password = $password;
$_dbObj = new mysqli($this->_host,$this->_user,$this->_password,$this->_database,$this->_port);
$this->_dbObj = $_dbObj;
return $this;
}else{
$this->error = mysqli_error($this->_dbObj);
return false;
}
}
/*
* 查詢資料庫中所有的表名
* @access public
* @return array 資料表的數量和表名
* */
public function tables(){
$sql = 'show tables';
$search_res = mysqli_query($this->_dbObj,$sql);
if($search_res){
$num_rows = $search_res->num_rows;
$tables_msg = array(
'count'=>$num_rows,
'tables'=>array()
);
for($i=0;$i<$num_rows;$i++){
$row = $search_res->fetch_assoc();
$key = 'Tables_in_'.$this->_database;
array_push($tables_msg['tables'],$row[$key]);
}
mysqli_free_result($search_res);
return $tables_msg;
}else{
mysqli_free_result($search_res);
return false;
}
}
/*
* 獲取指定表中所有資訊
* @access public
* @param string $table 資料表名稱
* @return array 資料表的詳細資訊
* */
public function select_table($table){
$sql = 'select * from '.$table;
$search_res = mysqli_query($this->_dbObj,$sql);
if($search_res){
$this->_table = $table;
$table_msg = self::query_handle($search_res);
$this->_tableObj = $table_msg;
mysqli_free_result($search_res);
return $table_msg;
}else{
mysqli_free_result($search_res);
return false;
}
}
/*
* 獲取指定表的欄位詳細資訊
* @access public
* @param string $table 資料表名稱
* @return array 資料表的欄位詳細資訊
* */
public function select_table_fields($table){
$sql = 'show fields from '.$table;
$search_res = mysqli_query($this->_dbObj,$sql);
if($search_res){
$this->_table = $table;
$fields_msg = self::query_handle($search_res);
mysqli_free_result($search_res);
return $fields_msg;
}else{
mysqli_free_result($search_res);
return false;
}
}
/*
* 獲取資料表中指定欄位資訊(允許多欄位同時查詢)
* @access public
* @param mixed $field 指定欄位(字串傳入使用,間隔)
* @return array 資料表中指定欄位資訊
* */
public function getField($field){
$fields = self::param_handle($field);
$count = count($fields);
for($i=0;$i<$count;$i++){
$index = $fields[$i];
$sql = 'select '.$index.' from '.$this->_table;
$res = mysqli_query($this->_dbObj,$sql);
$field_msg[$index] = self::query_handle($res);
}
return $field_msg;
}
/*
* mysqli_query函式結果處理函式
* @access protected
* @param object $obj mysqli_query函式結果
* @return array 資料表中指定欄位資訊
* */
protected function query_handle($obj){
$res = array();
for($i=0;$i<$obj->num_rows;$i++){
$row = $obj->fetch_assoc();
array_push($res,$row);
}
return $res;
}
/*
* 傳入引數處理函式
* @access protected
* @param mixed $param 傳入引數
* @return array 處理後陣列資料
* */
public function param_handle($param){
if(is_string($param)&&!empty($param)){
$params = explode(',',$param);
}elseif(is_array($param)&&!empty($param)){
$params = $param;
}else{
return false;
}
return $params;
}
/*
* 查詢表示式引數處理函式
* @access protected
* @param mixed $param 傳入引數(where limit order)
* @return string 處理後字串資料
* */
public function options_handle($param){
if(is_numeric($param)){
$option = $param;
}elseif(is_string($param)&&!empty($param)&&!is_numeric($param)){
$params = explode(',',$param);
$count = count($params);
$option = implode(' and ',$params);
}elseif(is_array($param)&&!empty($param)){
$params = $param;
$count = count($params);
$arr = array();
foreach($param as $key=>$value){
$tip = "$key=$value ";
array_push($arr,$tip);
}
$option = implode(' and ',$arr);
}else{
return false;
}
return $option;
}
/*
* 查詢表示式$options處理函式
* @access protected
* @return string 處理後字串資料
* */
protected function option(){
$options = $this->options;
$option = '';
if(isset($options['where'])){
$option .= 'where '.$options['where'].' ';
}
if(isset($options['order'])){
$option .= 'order by '.$options['order'].' '.$options['order_type'].' ';
}
if(isset($options['limit'])){
$option .= 'limit '.$options['limit'];
}
return $option;
}
/*
* 根據查詢表示式查詢資料(符合條件的所有記錄)
* @access public
* @return array 滿足查詢表示式的特定資料
* */
public function find(){
$option = self::option();
$sql = 'select * from '.$this->_table.' '.$option;
$search_res = mysqli_query($this->_dbObj,$sql);
$msg = self::query_handle($search_res);
return $msg;
}
/*
* 查詢表示式 where處理函式
* @access public
* @param mixed $where where查詢條件
* @return object $this
* */
public function where($where){
$this->options['where'] = self::options_handle($where);
return $this;
}
/*
* 查詢表示式 limit處理函式
* @access public
* @param mixed $limit limit查詢條件(數字)
* @return object $this
* */
public function limit($limit){
$this->options['limit'] = self::options_handle($limit);
return $this;
}
/*
* 查詢表示式 order處理函式
* @access public
* @param string $order order查詢條件
* @param string $type order查詢條件的順序(預設降序)
* @return object $this
* */
public function order($order,$type='desc'){
$this->options['order'] = $order;
$this->options['order_type'] = $type;
return $this;
}
/*
* 資料處理函式(最多處理二維資料)
* @access public
* @param array $data 需要插入的資料
* @return object $this
* */
public function data(array $data){
$values = array();
$fields = array();
if(is_array($data)){
foreach($data as $key=>$value){
if(is_array($value)){ //二維陣列
$tip = 1;
array_push($values,'('.implode(',',array_values($value)).')');
array_push($fields,'('.implode(',',array_keys($value)).')');
}else{ //一維陣列
$tip = 0;
}
}
}else{
return false;
}
if(!$tip){
array_push($values,'('.implode(',',array_values($data)).')');
array_push($fields,'('.implode(',',array_keys($data)).')');
}
$this->data['fields'] = $fields[0];
$this->data['values'] = implode(',',$values);
return $this;
}
/*
* 資料新增函式
* @access public
* @return mixed 資料庫新增資訊
* */
public function add(){
$fields = $this->data['fields'];
$values = $this->data['values'];
$sql = 'INSERT INTO '.$this->_table.$fields.'VALUES'.$values;
$res = mysqli_query($this->_dbObj,$sql);
return $res;
}
/*
* 資料更新函式(一維陣列)
* @access public
* @param array $data 需要更新的資料
* @return mixed 資料庫新增資訊
* */
function save(array $data){
$tip = array();
if(is_array($data)){
foreach($data as $key=>$value){
array_push($tip,"$key=$value");
}
}else{
return false;
}
$set_msg = implode(',',$tip);
$sql = 'UPDATE '.$this->_table.' SET '.$set_msg.' WHERE '.$this->options['where'];
$res = mysqli_query($this->_dbObj,$sql);
return $res;
}
/*
* 資料刪除函式
* @access public
* @return mixed 資料庫刪除資訊
* */
public function delete(){
$sql = 'DELETE FROM '.$this->_table.' WHERE '.$this->options['where'];
$res = mysqli_query($this->_dbObj,$sql);
return $res;
}
/*
* SQL語句查詢
* */
public function query($sql){
$search_res = mysqli_query($this->_dbObj,$sql);
return $search_res;
}
/*
* mysql中查詢語句
* */
protected function sql(){
/*
* 基本SQL語句
* 插入資料:INSERT INTO tb_name(id,name,score)VALUES(NULL,'張三',140),(NULL,'張四',178),(NULL,'張五',134);
* 更新語句:UPDATE tb_name SET score=189 WHERE id=2;
* 刪除資料:DELETE FROM tb_name WHERE id=3;
* WHERE語句:SELECT * FROM tb_name WHERE id=3;
* HAVING 語句:SELECT * FROM tb_name GROUP BY score HAVING count(*)>2
* 相關條件控制符:=、>、<、<>、IN(1,2,3......)、BETWEEN a AND b、NOT AND 、OR Linke()用法中 % 為匹配任意、 _ 匹配一個字元(可以是漢字)IS NULL 空值檢測
* MySQL的正則表示式:SELECT * FROM tb_name WHERE name REGEXP '^[A-D]' //找出以A-D 為開頭的name
* */
}
/*
* 關閉連線
* */
public function close(){
$close = mysqli_close($this->_dbObj);
if($close){
return true;
}else{
return false;
}
}
function __destruct(){
mysqli_close($this->_dbObj);
}
}