您的位置:首页 > 编程语言 > PHP开发

一个关于php使用pdo方式进行数据库连接和处理的类

2016-08-06 15:24 901 查看
话不多说,先贴代码

<?php
/**
@DB Operates For PDO
@author:MeeeeN
@date:2015-10-22 22:40:32
**/

//定义数据库信息

header("Content-type:text/html; charset=utf-8");

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PWD', '');
define('DB_NAME', 'lesson');

class DBPDO {

private static $instance;
public $dsn;
public $dbuser;
public $dbpwd;
public $sth;
public $dbh;

//初始化
function __construct() {
$this->dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
$this->dbuser = DB_USER;
$this->dbpwd = DB_PWD;
$this->connect();
$this->dbh->query("SET NAMES 'UTF8'");
$this->dbh->query("SET TIME_ZONE = '+8:00'");
}

//连接数据库
public function connect() {
try {
$this->dbh = new PDO($this->dsn, $this->dbuser, $this->dbpwd);
}
catch(PDOException $e) {
exit('连接失败:'.$e->getMessage());
}
}

//获取表字段
public function getFields($table='vista_order') {
$this->sth = $this->dbh->query("DESCRIBE $table");
$this->getPDOError();
$this->
a6df
;sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $this->sth->fetchAll();
$this->sth = null;
return $result;
}

//插入数据
public function insert($sql) {
if($this->dbh->exec($sql)) {
$this->getPDOError();
return $this->dbh->lastInsertId();
}
return false;
}

//删除数据
public function delete($sql) {
if(($rows = $this->dbh->exec($sql)) > 0) {
$this->getPDOError();
return $rows;
}
else {
return false;
}
}

//更改数据
public function update($sql) {
if(($rows = $this->dbh->exec($sql)) > 0) {
$this->getPDOError();
return $rows;
}
return false;
}

//获取数据
public function select($sql) {
$this->sth = $this->dbh->query($sql);
$this->getPDOError();
$this->sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $this->sth->fetchAll();
$this->sth = null;
return $result;
}

//获取数目
public function count($sql) {
$count = $this->dbh->query($sql);
$this->getPDOError();
return $count->fetchColumn();
}

//获取PDO错误信息
private function getPDOError() {
if($this->dbh->errorCode() != '00000') {
$error = $this->dbh->errorInfo();
exit($error[2]);
}
}

//关闭连接
public function __destruct() {
$this->dbh = null;
}
}

//eg: an example for operate select

$test = new DBPDO;

$sql = "SELECT * FROM `vista_order` WHERE `id`!=100 ";

$rs = $test->select($sql);

print_r($rs);

?>


这是之前研究了一段时间pdo后所写出来的一个pdo数据库相关操作类(比较懒,一直没更新博客),参考了一些网上的相关文章,但是感觉很多要么写得有错误,要么很啰嗦,所以自己搞了个,其实本来我是一直是用mysql类连接的,但是升级了php版本后发现不支持mysql方式连接了,又感觉mysqli比较啰嗦,所以索性改为用pdo,其实基本功能来说的话,这个类中construct,connection,destruct三个function就足够了,不过方便快速使用的话还是多写了一些function,个人感觉这个类的可移植性还是蛮高的,最后有使用的例子,基本上引用DBPDO类之后,只要自己写好sql语句,增删改查就都可以实现了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: