自己封装了一个PDO类

@Ta 2014-11-08 3763点击
<?php
class My_pdo{
private $user; //数据库用户
private $pwd; //数据库密码
private $host; //数据库地址
private static $pdo; //PDO对象
private static $my_pdo; //My_pdo对象
private $dbname; //数据库名

//构造方法
function __construct(){
//echo CONFIG_DIR;
require(CONFIG_DIR);
if(!self::$pdo){
$this->host=$host;
$this->user=$user;
$this->pwd=$password;
//echo $dbname.$host;
if($dbname){
$this->dbname=$dbname;
$dsn="mysql:host=$host;dbname=$dbname";
}else{
$dsn="mysql:host=$host";
}
try{
$arr=array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC);
$pdo=new PDO($dsn,$this->user,$this->pwd,$arr);
}catch(PDOException $e){
echo '数据库链接失败'.$e->getMessage();
exit;
}
self::$pdo=$pdo;
}
}
//dml语句执行,针对insert delete 语句等!
function setMy_pdo(My_pdo $my_pdo)
{
self::$my_pdo=$my_pdo;
}
static function getMy_pdo(){
return self::$my_pdo;
}
function execute_dml($dml){
try{
$res=self::$pdo->exec($dml);
}catch (PDOException $e){
echo '数据库语句错误'.$e->getMessage();
exit;
}
if($res==false){
return false;
}else{
return $res;
}
}
//dql语句执行,针对select语句等!
function execute_dql($dql){
try{
$res=self::$pdo->query($dql);
}catch (PDOException $e){
echo '数据库语句错误'.$e->getMessage();
exit;
}
return $res;
//$res->fetch($fetch_method);


}
//获取单行多列数据
function fetch($sql){
$res=$this->execute_dql($sql);
return $res->fetch();
}
//获去多行多列数据数据 
function fetchAll($sql){
$res=$this->execute_dql($sql);
return $res->fetchAll();
}
//获取上一次操作产生的Id
function getLastId(){
return $this->pdo->lastInsertId();
}
//获取单行单列数据
function fetchOne($sql){
$res=$this->execute_dql($sql);
return $res->fetch(PDO::FETCH_NUM)[0];
}

}
?>$pdo=new My_pdo();
$pdo->setMy_pdo($pdo); //设置对象<?php
abstract class PModel{
protected $my_pdo;
final function getMy_pdo(){
$this->my_pdo=My_pdo::getMy_pdo();
}
}
?>
回复列表(5|隐藏机器人聊天)
添加新回复
回复需要登录