PHP MySQL工具類的簡單封裝
阿新 • • 發佈:2019-01-07
<?php
/*
mysql資料庫操作類
0、實現了單例模式
1、該類一例項化,就可以自動連線上mysql資料庫
2、該類可以單獨去設定要使用的連線編碼
3、該類可以單獨設定要使用的資料庫
4、可以主動關閉資料庫連線
5、完成了DML、DQL操作的簡單封裝
6、實現了簡單的sql執行錯誤處理
*/
class MySQLDB{
private $link = null; #用於儲存連線資料庫成功後的“資源”
protected $host;
protected $port;
protected $user;
protected $password;
protected $charset;
protected $dbname;
/**
單例實現
//*/
private static $instance = null; #用於儲存該類的唯一例項
private function __clone(){} #禁止該類的例項物件進行克隆複製物件
#對外提供一個建立該類例項的方法
public static function getInstance($config){
if(!(static::$instance instanceof self)){
static::$instance = new self($config);
}
return static::$instance;
}
#實現單例的基礎:私有化該類的構造方法
private function __construct($config){
$this->host = isset($config['host'])?$config['host']:'localhost';
$this->port = isset($config['port'])?$config['port']:'3306';
$this->user = isset($config['user'])?$config['user']:'root';
$this->password = isset($config['password'])?$config['password']:'root';
$this->charset = isset($config['charset'])?$config['charset']:'utf8';
$this->dbname = isset($config['dbname'])?$config['dbname']:'db_mvc';
$this->link = @mysql_connect(
"{$this->host}:{$thi->port}","{$this->user}","$this->password")
or die(連線失敗!);
$this->selectDB($this->dbname);
$this->setCharset($this->charset);
}
public function setCharset($charset){#1設定連線環境字元編碼
$sql = "set names {$charset}";
$this->query($sql);
}
public function selectDB($dbname){#2選擇要操作的資料庫
$sql = "use {$dbname}";
$this->query($sql);
}
public function closeDB(){#3關閉資料庫連線
if(isset($this->link)){
mysql_query($this->link);
}
}
public function execute($sql){#增刪改
$this->query($sql);
return true;
}
public function getData($sql){#返回結果是一個標量值
$result = $this->query($sql);
$num = mysql_fetch_array($result);
mysql_free_result($result);
return $num[0];
}
public function getRow($sql){#返回結果是一個一維陣列
$result = $this->query($sql);
$row = mysql_fetch_array($result);
mysql_free_result($result);
return $row;
}
public function getRows($sql){#返回結果是一個二維陣列
$result = $this->query($sql);
$arr = array();
while($row = mysql_fetch_array($result)){
$arr[] = $row;
}
mysql_free_result($result);
return $arr;
}
private function query($sql){#錯誤處理並返回一個結果集
$result = mysql_query($sql);
if($result === false){
echo "程式碼執行錯誤!請參考如下提示:";
echo "<br />錯誤代號:".mysql_errno();
echo "<br />錯誤內容:".mysql_error();
echo "<br />錯誤程式碼:".$sql;
die();
}
return $result;
}
}
?>