<1>使用pdo操作mysql数据库
使用了单例模式封装了数据库操作,主要包括以下几步
①首先声明一个静态变量,便于数据库连接状态存储
②声明构造方法为私有,禁止外部调用构造方法进行连接数据库操作
③声明一个公有的获取数据连接属性的静态方法,便于外部直接调用,该方法首先判断静态变量是否存在,不存在则实例化自身类获取连接属性,存在则直接返回连接属性
④声明一个私有的克隆魔术方法__clone,目的是在有克隆对象操作的时候,自动调用,因方法为空,起到了克隆到的属性为空的作用,从而避免了连接属性的盗用
具体代码实现如下:MysqlPdo.class.php
<?php
class MysqlPdo{
protected static $_instance = null;
protected $dsn;
protected $dbh;
private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset){
try {
$this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;
$this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
$this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');
} catch (PDOException $e) {
$this->outputError($e->getMessage());
}
}
private function __clone(){
}
public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset){
if(self::$_instance === null){
self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
}
return self::$_instance;
}
public function query($strSql, $queryMode = 'All', $debug = false)
{
if ($debug === true) $this->debug($strSql);
$recordset = $this->dbh->query($strSql);
$this->getPDOError();
if ($recordset) {
$recordset->setFetchMode(PDO::FETCH_ASSOC);
if ($queryMode == 'All') {
$result = $recordset->fetchAll();
} elseif ($queryMode == 'Row') {
$result = $recordset->fetch();
}
} else {
$result = null;
}
return $result;
}
public function update($table, $arrayDataValue, $where = '', $debug = false)
{
$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)."')";
}
if ($debug === true) $this->debug($strSql);
$result = $this->dbh->exec($strSql);
$this->getPDOError();
return $result;
}
public function insert($table, $arrayDataValue, $debug = false)
{
$this->checkFields($table, $arrayDataValue);
$strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
if ($debug === true) $this->debug($strSql);
$result = $this->dbh->exec($strSql);
$this->getPDOError();
return $result;
}
public function delete($table, $where = '', $debug = false)
{
if ($where == '') {
$this->outputError("'WHERE' is Null");
} else {
$strSql = "DELETE FROM `$table` WHERE $where";
if ($debug === true) $this->debug($strSql);
$result = $this->dbh->exec($strSql);
$this->getPDOError();
return $result;
}
}
//直接执行增删改sql语句
public function execSql($strSql, $debug = false)
{
if ($debug === true) $this->debug($strSql);
$result = $this->dbh->exec($strSql);
$this->getPDOError();
return $result;
}
//预处理执行
public function prepareSql($sql=''){
return $this->dbh->prepare($sql);
}
//执行预处理
public function execute($presql){
return $this->dbh->execute($presql);
}
/**
* 获取字段最大值
*
* @param string $table 表名
* @param string $field_name 字段名
* @param string $where 条件
*/
public function getMaxValue($table, $field_name, $where = '', $debug = false)
{
$strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
if ($where != '') $strSql .= " WHERE $where";
if ($debug === true) $this->debug($strSql);
$arrTemp = $this->query($strSql, 'Row');
$maxValue = $arrTemp["MAX_VALUE"];
if ($maxValue == "" || $maxValue == null) {
$maxValue = 0;
}
return $maxValue;
}
/**
* 获取指定列的数量
*
* @param string $table
* @param string $field_name
* @param string $where
* @param bool $debug
* @return int
*/
public function getCount($table, $field_name, $where = '', $debug = false)
{
$strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
if ($where != '') $strSql .= " WHERE $where";
if ($debug === true) $this->debug($strSql);
$arrTemp = $this->query($strSql, 'Row');
return $arrTemp['NUM'];
}
/**
* 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();
$recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
$this->getPDOError();
$recordset->setFetchMode(PDO::FETCH_ASSOC);
$result = $recordset->fetchAll();
foreach ($result as $rows) {
$fields[] = $rows['Field'];
}
return $fields;
}
/**
* getPDOError 捕获PDO错误信息
*/
private function getPDOError()
{
if ($this->dbh->errorCode() != '00000') {
$arrayError = $this->dbh->errorInfo();
$this->outputError($arrayError[2]);
}
}
/**
* debug
*
* @param mixed $debuginfo
*/
private function debug($debuginfo)
{
var_dump($debuginfo);
exit();
}
/**
* 输出错误信息
*
* @param String $strErrMsg
*/
private function outputError($strErrMsg)
{
throw new Exception('MySQL Error: '.$strErrMsg);
}
/**
* destruct 关闭数据库连接
*/
public function destruct()
{
$this->dbh = null;
return 0;
}
}
<2>使用mysqli操作mysql的常用封装
该封装有两个类,其中一个类是抽象类,定义了数据库操作的常用抽象方法,另一个类继承抽象类,并且重写了具体的数据库操作方法,具体代码实现如下:MysqlI.class.php
<?php
abstract class aDB {
/**
* 连接数据库,从配置文件中读取配置信息
*/
abstract public function conn();
/**
* 发送query查询
* @param string $sql sql??
* @return mixed
*/
abstract public function query($sql);
/**
* 查询多行数据
* @param string $sql sql语句
* @return array
*/
abstract public function getAll($sql);
/**
* 单行数据
* @param string $sql sql语句
* @return array
*/
abstract public function getRow($sql);
/**
* 查询单个数据 count(*)
* @param string $sql sql语句
* @return mixed
*/
abstract public function getOne($sql);
/**
* 自动创建sql并执行,insert/update
* @param array $data 关联数组 键/值 与表的 列/值对应
* @param string $table 表明
* @param string $act 动作/update/insert
* @param string $where 条件,用于update
* @return int 新插入的行的主键值或者影响行数
*/
abstract public function Exec($data , $table , $act='insert' , $where='0');
/**
* 返回上一条insert语句产生的值
*/
abstract public function lastId();
/**
* 返回上一条语句影响的行数
*/
abstract public function affectRows();
}
class MyMysqlI extends aDB{
public $mysqli;
public $conf;
public function __construct($config){
$this->conf=$config;
$this->conn();
}
/**
* 连接数据库,从配置文件中读取配置信息
*/
public function conn(){
//$conf=include './conf.php';
$this->mysqli = new mysqli($this->conf['host'], $this->conf['user'], $this->conf['pwd'], $this->conf['db']);
//设置字符集
$this->mysqli->query('set names '.$this->conf['charset']);
}
/**
* 发送query查询
* @param string $sql sql??
* @return mixed
*/
public function query($sql){
//select返回一个对象或者无结果集sql返回bool
return $this->mysqli->query($sql);
}
/**
* 查询多行数据
* @param string $sql sql语句
* @return array
*/
public function getAll($sql){
$data=[];
$res=$this->mysqli->query($sql);
while($row=$res->fetch_assoc()){
$data[]=$row;
}
return $data;
}
/**
* 单行数据
* @param string $sql sql语句
* @return array
*/
public function getRow($sql){
$res=$this->mysqli->query($sql);
return $res->fetch_assoc();
}
/**
* 查询单个数据 count(*)
* @param string $sql sql语句
* @return mixed
*/
public function getOne($sql){
$res=$this->mysqli->query($sql);
return $res->fetch_row()[0];
}
/**
* 自动创建sql并执行,insert/update
* @param array $data 关联数组 键/值 与表的 列/值对应
* @param string $table 表明
* @param string $act 动作/update/insert
* @param string $where 条件,用于update
* @return int 新插入的行的主键值或者影响行数
*/
public function Exec($data , $table , $act='insert' , $where='0'){
if($act == 'insert'){
$sql ="insert into $table (";
$sql.=implode(',',array_keys($data)).") values('";
$sql.=implode(array_values($data),"','")."')";
}else{
$sql="update $table set ";
foreach($data as $k => $v){
$sql.=$k."='".$v."',";
}
$sql=rtrim($sql,',')." where ".$where;
}
return $this->mysqli->query($sql);
}
/**
* 返回上一条insert语句产生的值
*/
public function lastId(){
return $this->mysqli->insert_id;
}
/**
* 返回上一条语句影响的行数
*/
public function affectRows(){
return $this->mysqli->affected_rows;
}
}