PHP封装PDO之单例模式实现增删改查
•技术分享
561
0
class Db{
//存储 类的实例化对象
private static $instance;
//存储pdo类的实例化
private $pdo;
//存储PDOStament
private $stmt;
//禁止外部 new 类
private function __construct($config,$port,$charset){
try{
$this->pdo = new PDO('mysql:host='.$config['host'].';dbname='.$config['dbname'].';port='.$port.';charset='.$charset,$config['user'],$config['password']);
//$this->pdo ->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
header("Content-type: text/html;charset=utf-8");
echo 'mysql connect error:'.$e->getMessage();
}
}
//对外访问的方法 实现 类的实例
public static function getInstance($config,$port=3306,$charset="utf8"){
//判断是否有实例化 没有实例化 有 直接返回实例化
if(!self::$instance instanceof Db ) self::$instance = new self($config,$port,$charset);
return self::$instance;
}
//插入数据
public function insertData($table,$data){
//拼接插入的字段名
$columns = implode(',',array_keys($data));
//拼接占位符
$values = ':'.implode(',:',array_keys($data));
$sql = "INSERT INTO $table ($columns) VALUES($values)";
$newData = $this->doData($data);
$this->exe($sql,$newData);
if($this->stmt->errorCode()==00000) return $this->pdo->lastInsertId();
else return $this->stmt->errorInfo()[2];
}
//更新数据
public function updateData($table,$data,$where){
//$sql = "UPDATE user SET user_name=:name WHERE id=:id";
//加个判断 判断$where是否在数据表存在
$res = $this->getData($table,array_keys($data),$where);
if(!$res) return '不存在你要更新的数据';
$columns = '';
foreach($data as $k=>$v) $columns.=$k.'=:'.$k.',';
$columns = trim($columns,',');
$sql = "UPDATE $table SET $columns ".$where;
$newData = $this->doData($data);
$this->exe($sql,$newData);
if($this->stmt->errorCode()==00000) return 1;
else return $this->stmt->errorInfo()[2];
}
// 查询数据
public function getData($table,$fields,$where=null,$one=true){
if(count($fields)>1) $columns = implode(',',array_values($fields));
else $columns = $fields[0];
$sql = "SELECT $columns FROM $table ".$where;
$this->exe($sql);
if($this->stmt->errorCode()==00000){
if($one) return $this->stmt->fetch(PDO::FETCH_ASSOC);
else return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}else return $this->stmt->errorInfo()[2];
}
//删除数据
public function deleteData($table,$where){
if(!$where) return '缺少删除条件';
$sql = "DELETE FROM $table ".$where;
$res = $this->getData($table,['*'],$where);
if(!$res) return '不存在你要删除的数据';
$this->exe($sql);
if($this->stmt->errorCode()==00000) return 1;
else return $this->stmt->errorInfo()[2];
}
//处理插入的数据
private function doData($data){
foreach($data as $k=>$v){
$key = ':'.$k;
$newData[$key]=$v;
}
return $newData;
}
//执行sql语句
private function exe($sql,$data=null){
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
//禁止外部 克隆对象
private function __clone(){}
}
单例模式:私有的构造方法,私有的静态属性,共有的静态getInstance()方法获取对象。
插入数据方法:insertData($table,$data)参数是表名,和数据。
更新数据方法:updateData($table,$data,$where) 参数是表名,数据还有条件。
删除数据方法:deleteData($table,$where) 参数是表名,和条件。
查询数据方法:getData($table,$fields,$where=null,$one=true) 参数是表名,查询字段,条件,还有是是否查询单条数据。
具体调用方法:
require_once(dirname(__FILE__)."/db/Db.php");
$config=['host'=>'127.0.0.1','dbname'=>'test','user'=>'root','password'=>'root'];
$db = Db::getInstance($config);
$table = 'user';
// 插入数据
$data = ['user_name'=>'asdfasdfasdasdf','password'=>'asdfasd'];
echo $db->insertData($table,$data);
// 更新数据
echo $db->updateData($table,$data,' where id=7');
$fields = ['user_name','password'];
//查询单条
var_dump($db->getData($table,$fields,'WHERE id=2',true));
//查询多条
var_dump($db->getData($table,$fields));
//删除数据
var_dump($db->deleteData($table,'WHERE id=2'));
如另外文件调用:
require_once(dirname(__FILE__)."/db/DB.php");
$config=['host'=>'xx.xxx.com','dbname'=>'sjk','user'=>'ua','password'=>'123123'];
$GLOBALS['$db']=Db::getInstance($config); //定义为全局变量