【php高級】MySQLI類

<?php
include_once('config.inc.php');

class MysqliHelper{

private $host;//數據庫地址
private $user;//數據庫帳號
private $pwd;//數據庫密碼
private $db;//需要操作的數據


//構造函數,每次實例化時調用,初始化配置
function __construct($db='mysql'){
$this->db=$db;//默認爲二大系統數據庫之一,保證SQL語句都能執行
$this->host=HOST;
$this->user=USER;
$this->pwd=PWD;
}

//封裝需要操作的數據屬性
function setDb($value){
$this->db=$value;
}

function getDb(){
return $this->db;
}

/*
Describe:切換數據庫服務器
Paramters:
$host 數據庫服務器的地址
$user 數據庫服務器的帳號
$pwd 數據庫服務器的密碼
*/
function ChangeDBHost($host,$user,$pwd){
$this->host=$host;
$this->user=$user;
$this->pwd=$pwd;
}


/*
Describe:操作MYSQL數據庫
Paramters:$sql任何的SQL語句,$type=1默認引用數組,$type=2索引數組
Returns:讀取返回結果二維數組,添加/修改/刪除返回影響行數
*/
function Execute($sql,$type=1){
$mysqli=@new mysqli($this->host,$this->user,$this->pwd);
if($mysqli->connect_error)
die('連接數據庫服務器失敗,請檢查配置');
@$mysqli->select_db($this->db) or die('訪問的數據庫'.$this->db.'不存在,請重新輸入');
$mysqli->query("set names utf8");
$result=@$mysqli->query($sql);
if(substr_count($sql,"select ")==0)
{
$mysqli->close();//關閉鏈接釋放資源
return $result;
}
//$arr='';//讀取返回的二維數組
if($type==1){
while(@$row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
	$arr[]=$row;
	}
}
elseif($type==2){
while(@$row=mysqli_fetch_array($result,MYSQLI_NUM)){
	$arr[]=$row;
	}
}
$mysqli->close();
return $arr;
}

//批量執行SQL語句
function ExecuteMultiSql($sql){
$mysqli=@new mysqli($this->host,$this->user,$this->pwd);
if($mysqli->connect_error)
die('連接失敗,請檢查配置');
@$mysqli->select_db($this->db) or die('訪問的數據庫'.$this->db.'不存在');
$mysqli->multi_query($sql);
$mysqli->close();
}

/*
批量執行SQL語句 $sqls批量執行SQL語句,中間以;隔開
最後一條SQL查詢返回最後一個結果集
最後一條SQL插入、修改、刪除返回影響行數
*/
function ExecuteArr($sqls){
//1、創建mysqli對象
$mysqli=@new mysqli($this->host,$this->user,$this->pwd,$this->db);
if($mysqli->connect_error)
die("連接失敗".$mysqli->connect_error);
//2、處理結果
//如果成功,至少有一個結果集
if($res=$mysqli->multi_query($sqls)){
	while($mysqli->next_result()){
		$res=$mysqli->store_result();
		//必須強制跳出循環
		if(!$mysqli->more_results())
		break;
	}
}
//3、關閉資源
$mysqli->close();
return mysqli_fetch_array($res);
}

}
?>
發佈了83 篇原創文章 · 獲贊 12 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章