php封装的封装的pdo数据库操作工具类与用法示例数据库操作工具类与用法示例
本文实例讲述了php封装的pdo数据库操作工具类与用法。分享给大家供大家参考,具体如下:
<?php
header("Content-Type:text/html;charset=utf-8");
class PdoMysql{
public static $config = array();//设置连接参数,配置信息
public static $link = null;//保存连接标识符
public static $pconnect = false;//是否开启长连接
public static $dbVersion = null;//保存数据库版本
public static $connected = false;//判断是否连接成功
public static $PDOStatement = null;//保证PDOStatement对象
public static $queryStr = null;//保存最后执行的操作
public static $error = null;//保存错误信息
public static $lastInsertId = null;//保存上一步插入操作保存的AUTO_INCREMANT
public static $numRows = null;//受影响记录的条数
/**
* 构造函数,连接数据库
*
* @param array|string $dbConfig The database configuration
*
* @return boolean ( description_of_the_return_value )
*/
public function __construct($dbConfig=''){
if(!class_exists("PDO")){
self::throw_exception("不支持PDO,请先开启");
}
if(!is_array($dbConfig)){
$dbConfig = array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '1234',
'database' => 'test',
'hostport' => '3306',
'dbms' => 'mysql',
'dsn' => 'mysql:host=localhost;dbname=test'
);
}
if(empty($dbConfig['hostname'])){
self::throw_exception("没有定义数据库配置,请先定义");
}
self::$config = $dbConfig;
if(empty(self::$config['params'])){
self::$config['params'] = array();
}
if(!isset(self::$link)){
$configs = self::$config;
if(self::$pconnect){
//开启长连接,添加到配置数组中
$configs['params'][constant("PDO::ATTR_PERSISTENT")] = true;
}
try {
self::$link = new PDO($configs['dsn'],$configs['username'],$configs['password'],$configs['params']);
} catch (PDOException $e) {
self::throw_exception($e->getMessage());
}
if(!self::$link){
self::throw_exception("PDO连接错误");
return false;
}
self::$link->exec("set names utf8");
self::$dbVersion = self::$link->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
unset($configs);
}
}
/**
* 得到所有记录
*
* @param <type> $sql The sql
*
* @return <type> All.
*/
public static function getAll($sql=null){
if($sql!=null){
self::query($sql);
}
$result = self::$PDOStatement->fetchAll(constant("PDO::FETCH_ASSOC"));