使用單列模式鏈接pdo並操作
<?php
class MyPDO{
private $type; //資料庫類型
private $host; //主機地址
private $port; //埠號
private $dbname; //資料庫名
private $charset; //字元編碼
private $user; //用戶名
private $pwd; //密碼
private $pdo; //pdo對象
private static $instance;
private function __construct($param){
$this->initParam($param);
$this->initPDO();
$this->initException();
}
private function __clone(){
}
//初始化參數
private function initParam($param){
$this->type=isset($param[type])?$param[type]:mysql;
$this->host=isset($param[host])?$param[host]:localhost;
$this->port=isset($param[port])?$param[port]:3306;
$this->dbname=isset($param[dbname])?$param[dbname]:;
$this->charset=isset($param[charset])?$param[charset]:utf8;
$this->user=isset($param[user])?$param[user]:;
$this->pwd=isset($param[pwd])?$param[pwd]:;
}
//連接資料庫
private function initPDO(){
try{
$dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";
$this->pdo=new PDO($dsn,$this->user,$this->pwd);
}catch(PDOException $ex){
$this->showException($ex);
}
}
//設置異常模式
private function initException(){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
//封裝顯示異常信息
private function showException($ex,$sql=){
if($sql!=){
echo SQL語句執行失敗<br>;
echo 錯誤的SQL語句是:.$sql,<br>;
}
echo 錯誤編號:.$ex->getCode(),<br>;
echo 錯誤文件:.$ex->getFile(),<br>;
echo 錯誤行號:.$ex->getLine(),<br>;
echo 錯誤信息:.$ex->getMessage(),<br>;
exit;
}
//執行數據操作語句
public function exec($sql){
try{
return $this->pdo->exec($sql);
} catch (PDOException $ex) {
$this->showException($ex, $sql);
}
}
//獲取插入記錄的自動增長的編號
public function getLastInsertId(){
return $this->pdo->lastInsertId();
}
//封裝匹配的類型
private function fetchType($type){
switch($type){
case assoc:
return PDO::FETCH_ASSOC;
case num:
return PDO::FETCH_NUM;
case both:
return PDO::FETCH_BOTH;
default:
return PDO::FETCH_ASSOC;
}
}
//獲取所有記錄,返回二維數組
public function fetchAll($sql,$type=assoc){
try{
$stmt=$this->pdo->query($sql);
$type= $this->fetchType($type);
return $stmt->fetchAll($type);
} catch (PDOException $ex){
$this->showException($ex, $sql);
}
}
//匹配一行
public function fetchRow($sql,$type=assoc){
try{
$stmt=$this->pdo->query($sql);
$type= $this->fetchType($type);
return $stmt->fetch($type);
}catch(PDOException $ex){
$this->showException($ex, $sql);
}
}
//匹配一行一列
public function fetchColumn($sql){
try{
$stmt=$this->pdo->query($sql);
return $stmt->fetchColumn();
} catch (Exception $ex) {
$this->showException($ex, $sql);
}
}
//獲取單例
public static function getInstance($param=array()){
if(!self::$instance instanceof self)
self::$instance=new self($param);
return self::$instance;
}
}
推薦閱讀:
※PHP運維自動化方向涉及哪些業務或工具開發么?有啥優勢或劣勢么?
※Zend引擎
※memcache的初級使用
※有哪些適合高並發、高性能網站的 PHP 框架推薦?
※php編寫擴展調用動態so庫