使用 PHP PDO 封装一个单例模式的数据库操作类。
MyPDO.php 代码如下:
实例
<?php
/**
* PDO-MySQL数据库操作类 单例模式
* @author Luocz
* @license https://runoops.com/
* @version v1.0.0
*/
class MyPDO
{
protected static $_instance = null;
protected $dsn;
protected $dbh;
protected $debug = false;
/**
* 构造方法
* @param Array $config
* @return MyPDO
*/
private function __construct($config = [])
{
try {
$type = isset($config['type']) ? $config['type'] : 'mysql';
$host = isset($config['host']) ? $config['host'] : '127.0.0.1';
$port = isset($config['port']) ? $config['port'] : '3306';
$user = isset($config['user']) ? $config['user'] : 'root';
$pwd = isset($config['pwd']) ? $config['pwd'] : 'root';
$dbname = isset($config['dbname']) ? $config['dbname'] : 'runoops-test';
$charset = isset($config['charset']) ? $config['charset'] : 'utf8';
$this->dsn = "{$type}:host={$host};port={$port};dbname={$dbname};charset={$charset}";
$this->dbh = new PDO($this->dsn, $user, $pwd);
// $this->dbh->exec('SET character_set_connection=' . $charset . ', character_set_results=' . $charset . ', character_set_client=binary');
} catch (PDOException $e) {
$this->outputError($e->getMessage());
}
}
/**
* 防止克隆
*
*/
private function __clone()
{
}
/**
* 单例实例
*
* @return Object
*/
public static function getInstance($config)
{
if (self::$_instance === null) {
self::$_instance = new self($config);
}
return self::$_instance;
}
/**
* 执行SQL
* @param $sql string 执行的SQL语句
* @return object PDOStatement
*/
public function query($sql)
{
$stmt = $this->dbh->query($sql);
if ($stmt === false) {
$error = $this->dbh->errorInfo();
$this->outputError("Query ERROR : {$error[1]}({$error[0]}): {$error[2]}");
}
return $stmt;
}
/**
* Query 查询所有数据
*
* @param String $strSql SQL语句
* @return Array
*/
public function fetchAll($strSql)
{
$stmt = $this->query($strSql);
if ($stmt) {
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
} else {
$result = null;
}
return $result;
}
/**
* 查询一条数据
*
* @param String $strSql SQL语句
* @return Array
*/
public function fetchRow($strSql)
{
$stmt = $this->query($strSql);
if ($stmt) {
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetch();
} else {
$result = null;
}
return $result;
}
/**
* 更新
*
* @param String $table 表名
* @param Array $arrayDataValue 字段与值
* @param String $where 条件
* @return Int
*/
public function update($table, $arrayDataValue, $where = '')
{
$this->checkFields($table, $arrayDataValue);
if ($where) {
$strSql = '';
foreach ($arrayDataValue as $key => $value) {
$strSql .= ", `$key`='$value'";
}
$strSql = substr($strSql, 1);
$strSql = "UPDATE `$table` SET $strSql WHERE $where";
} else {
$strSql = "REPLACE INTO `$table` (`" . implode('`,`', array_keys($arrayDataValue)) . "`) VALUES ('" . implode("','", $arrayDataValue) . "')";
}
$result = $this->dbh->exec($strSql);
return $result;
}
/**
* Insert 插入
*
* @param String $table 表名
* @param Array $arrayDataValue 字段与值
* @return Int
*/
public function insert($table, $arrayDataValue)
{
$this->checkFields($table, $arrayDataValue);
$strSql = "INSERT INTO `$table` (`" . implode('`,`', array_keys($arrayDataValue)) . "`) VALUES ('" . implode("','", $arrayDataValue) . "')";
$num = $this->dbh->exec($strSql);
if($num > 0){
return $this->dbh->lastInsertId();
}else{
return $num;
}
}
/**
* Replace 覆盖方式插入
*
* @param String $table 表名
* @param Array $arrayDataValue 字段与值
* @return Int
*/
public function replace($table, $arrayDataValue)
{
$this->checkFields($table, $arrayDataValue);
$strSql = "REPLACE INTO `$table`(`" . implode('`,`', array_keys($arrayDataValue)) . "`) VALUES ('" . implode("','", $arrayDataValue) . "')";
$result = $this->dbh->exec($strSql);
return $result;
}
/**
* 删除
*
* @param String $table 表名
* @param String $where 条件
* @return Int
*/
public function delete($table, $where = '')
{
if ($where == '') {
$this->outputError("'WHERE' is Null");
} else {
$strSql = "DELETE FROM `$table` WHERE $where";
$result = $this->dbh->exec($strSql);
return $result;
}
}
/**
* execSql 执行SQL语句
*
* @param String $strSql
* @return Int
*/
public function execSql($strSql)
{
$result = $this->dbh->exec($strSql);
return $result;
}
/**
* 获取指定列的数量
*
* @param string $table
* @param string $field_name
* @param string $where
* @return int
*/
public function getCount($table, $field_name, $where = '')
{
$strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
if ($where != '') $strSql .= " WHERE $where";
$arrTemp = $this->fetchRow($strSql);
return $arrTemp['NUM'];
}
/**
* 获取表引擎
*
* @param String $dbName 库名
* @param String $tableName 表名
* @return String
*/
public function getTableEngine($dbName, $tableName)
{
$strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='" . $tableName . "'";
$arrayTableInfo = $this->fetchAll($strSql);
return $arrayTableInfo[0]['Engine'];
}
/**
* beginTransaction 事务开始
*/
private function beginTransaction()
{
$this->dbh->beginTransaction();
}
/**
* commit 事务提交
*/
private function commit()
{
$this->dbh->commit();
}
/**
* rollback 事务回滚
*/
private function rollback()
{
$this->dbh->rollback();
}
/**
* transaction 通过事务处理多条SQL语句
* 调用前需通过getTableEngine判断表引擎是否支持事务
*
* @param array $arraySql
* @return Boolean
*/
public function execTransaction($arraySql)
{
$retval = 1;
$this->beginTransaction();
foreach ($arraySql as $strSql) {
if ($this->execSql($strSql) == 0) $retval = 0;
}
if ($retval == 0) {
$this->rollback();
return false;
} else {
$this->commit();
return true;
}
}
/**
* 设置debug
*/
public function setDebug($flag = false)
{
$this->debug = $flag;
}
/**
* checkFields 检查指定字段是否在指定数据表中存在
*
* @param String $table
* @param array $arrayField
*/
private function checkFields($table, $arrayFields)
{
$fields = $this->getFields($table);
foreach ($arrayFields as $key => $value) {
if (!in_array($key, $fields)) {
$this->outputError("Unknown column `$key` in field list.");
}
}
}
/**
* getFields 获取指定数据表中的全部字段名
*
* @param String $table 表名
* @return array
*/
private function getFields($table)
{
$fields = array();
$stmt = $this->query("SHOW COLUMNS FROM $table");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
foreach ($result as $rows) {
$fields[] = $rows['Field'];
}
return $fields;
}
/**
* 输出错误信息
*
* @param String $strErrMsg
*/
private function outputError($strErrMsg)
{
throw new Exception('MySQL Error: ' . $strErrMsg);
}
/**
* destruct 关闭数据库连接
*/
public function destruct()
{
$this->dbh = null;
}
}
使用示例:
实例
<?php
// 引入操作类
include 'MyPDO.php';
//测试
$dbconfig = [
'type' => 'mysql',
'host' => 'localhost',
'port' => 3306,
'dbname' => 'runoops-test',
'user' => 'root',
'pwd' => 'root',
'charset' => 'utf8',
];
//获取pdo单例实例
$mypdo= MyPDO::getInstance($dbconfig);
// 添加数据
// $insertId = $mypdo->insert('websites', ['name' => 'testDB2','url' => 'test2.xxx.com','alexa' => 100,'country' => 'CN']);
// echo 'insert id = ' . $insertId;
// echo '<br />';
// 更新数据,返回影响条数
// $numUp = $mypdo->update('websites', ['url' => 'test2.xxx2.com'],'name = "testDB2"');
// var_dump($numUp);
//获取websites 前10条
$list=$mypdo->fetchAll('select * from websites limit 10');
var_dump($list);
// $list=$mypdo->fetchRow('select * from websites where id = 1');
// var_dump($list);
//删除id=14的数据
// $mypdo->delete('websites','id=14');
?>
分享笔记