<?php
//http://www.imavex.com/php-pdo-wrapper-class/
class db extends PDO
{
private $error;
private $sql;
private $bind; public function __construct($dsn, $user = "", $passwd = "")
{
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';",
//PDO::ATTR_PERSISTENT => true, //长连接方式切换数据库暂不支持
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false //禁止php的prepare拼接sql,分两部分传递,彻底杜绝sql注入。
); try {
parent::__construct($dsn, $user, $passwd, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
throw new Exception($e);
}
} public function select($table, $fields = "", $where = "", $bind = array())
{
$sql = "SELECT " . $fields . " FROM " . $table;
if (!empty($where))
$sql .= " WHERE " . $where;
$sql .= ";";
return $this->run($sql, $bind);
} public function update($table, Array $info, $where, $bind = array())
{
$fields = $this->filter($table, $info); $sql = "UPDATE " . $table . " SET ";
for ($f = 0; $f < count($fields); ++$f) {
if ($f > 0)
$sql .= ", ";
$sql .= $fields[$f] . ' = ?';
}
$sql .= " WHERE " . $where . ";"; $bind = $this->cleanup($bind);
for ($i = count($fields) - 1; $i >= 0; $i--)
array_unshift($bind, $info[$fields[$i]]); return $this->run($sql, $bind);
} public function insert($table, Array $info)
{
$first = current($info);
if (!is_array($first)) { //如果是插入单个记录,组装成多个的形式
$info = array($info);
}
$fields = $this->filter($table, $info[0]);
$place_holders = '';
foreach ($info as $key => $v) {
if ($key > 0 ) {
$place_holders .= ',';
}
$place_holders .= '(' . implode(',', array_fill(0, count($fields), '?')) . ')';
}
$sql = "INSERT INTO " . $table . " (" . implode($fields, ", ") . ") VALUES $place_holders;";
$bind = array();
foreach ($info as $v) {
foreach ($fields as $field) {
array_push($bind, $v[$field]);
}
}
return $this->run($sql, $bind);
} public function delete($table, $where, $bind = array())
{
$sql = "DELETE FROM " . $table . " WHERE " . $where . ";";
$this->run($sql, $bind);
} private function filter($table, Array $info)
{
$driver = $this->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver == 'sqlite') {
$sql = "PRAGMA table_info('" . $table . "');";
$key = "name";
} elseif ($driver == 'mysql') {
$sql = "DESCRIBE " . $table . ";";
$key = "Field";
} else {
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" . $table . "';";
$key = "column_name";
} if (false !== ($list = $this->run($sql))) {
$fields = array();
foreach ($list as $record)
$fields[] = $record[$key];
return array_values(array_intersect($fields, array_keys($info)));
}
return array();
} private function cleanup(Array $bind)
{
if (!is_array($bind)) {
if (!empty($bind))
$bind = array($bind);
else
$bind = array();
}
return $bind;
} public function run($sql, $bind = array())
{
$this->sql = trim($sql);
$this->bind = $this->cleanup($bind);
$this->error = ""; //echo $realSql = $this->getRealSql() . "<BR>"; //获取真实sql,方便调试,如果是绑定模式,参数不一定是真实的(会被过滤),要去mysql日志下面看 try {
$pdostmt = $this->prepare($this->sql);
if ($pdostmt->execute($this->bind) !== false) {
if (preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
elseif (preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this->sql))
return $pdostmt->rowCount();
}
} catch (PDOException $e) {
//echo $this->error = $e->getMessage();
throw new Exception($e); //异常外抛,便于外面捕捉
return false;
}
} private function getRealSql()
{
$realSql = $this->sql;
if (count($realSql) > 0) {
foreach ($this->bind as $v) {
if (!is_numeric($v)) $v = '\'' . $v . '\'';
$realSql = preg_replace('/\?/', $v, $realSql, 1);
}
}
return $realSql;
}
}

  

pdo封装类的更多相关文章

  1. 自定义PDO封装类

    <?php class Db { protected static $_instance = null; // 定义标识符(通过$_instance值得改变情况,来判定Model类是否被实例化) ...

  2. php pdo封装类

    class MYPDO { protected static $_instance = null; protected $dbname = ''; protected $dsn; protected ...

  3. 学习到目前,自己封装的db类和pdo类

    DB封装类 <?php class DBDA { public $host = "localhost"; public $uid = "root"; pu ...

  4. 写了个简单的pdo的封装类

    <?php class PD { //造对象 public $dsn = "mysql:dbname=test2;host=localhost"; //数据库类型,数据库名和 ...

  5. php数据库操作封装类

    <?php /** * Desc: php操作mysql的封装类 * Author zhifeng * Date: 2015/04/15 * 连接模式:PDO */ class MMysql { ...

  6. PDO 增删改查封装的类

    Selecting Data 你在mysql_*中是这样做的 <?php $result = mysql_query('SELECT * from table') or die(mysql_er ...

  7. 比Mysqli操作数据库更简便的方式 。PDO

    下面来说一下PDO 先画一张图来了解一下 mysqli是针对mysql这个数据库扩展的一个类 PDO是为了能访问更多数据库 如果出现程序需要访问其他数据库的话就可以用PDO来做 PDO数据访问抽象层1 ...

  8. pdo的使用

    PHP 数据对象 (PDO) 扩展为PHP访问数据库定义了一个轻量级的一致接口. PDO 提供了一个数据访问抽象层,这意味着,不管使用哪种数据库,都可以用相同的函数(方法)来查询和获取数据. PDO随 ...

  9. PHP中PDO事务的使用方法

    事务 (Transaction) 是操作数据库中很重要的一个功能, 它可以让你预定一条, 或者一系列 SQL 语句, 然后一起执行. 在执行的过程中, 如果其中的某条执行失败, 可以回滚所有已更改的操 ...

随机推荐

  1. HDU 4292 Food 最大流

    Food Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  2. XML引入多scheme文件约束简单示例

    XML引入多scheme文件约束简单示例,用company.xsd和department.xsd来约束company.xml: company.xsd <?xml version="1 ...

  3. contentprovider的学习实例总结

    工作中遇到了contentprovider数据共享机制,下面来总结一下: 一.ContentProvider简介       当应用继承ContentProvider类,并重写该类用于提供数据和存储数 ...

  4. JVM的栈内存

    每当启动一个新线程时,Java虚拟机都会为它分配一个Java栈.Java栈以帧为单位保存线程的运行状态.虚拟机只会直接对Java栈执行两种操作:以帧为单位的压栈和出栈. 某个线程正在执行的方法被称为该 ...

  5. HTML-a

    链接的其他使用 电话 <a href="tel:(phonenumber)">Tel</a> 短信 <a href="sms:(phonen ...

  6. jquery.validate.js的remote用法

    <script> $(function(){ $("#myform").validate( { rules: { name:{required:true,rangele ...

  7. BFS+模拟 ZOJ 3865 Superbot

    题目传送门 /* BFS+模拟:dp[i][j][p] 表示走到i,j,方向为p的步数为多少: BFS分4种情况入队,最后在终点4个方向寻找最小值:) */ #include <cstdio&g ...

  8. 设置完在Canvas的位置后,控件HitTest不响应的问题

    have a Canvas with a couple of elements on it like Line, Path and Text Box. In the MouseOver event o ...

  9. hihoCoder 1160 攻城略地

    原图可能有多个连通分量,先DFS找出每个连通分量中最小节点,这些必然是要攻占的城市. 设 n 为节点数, m 为边数, cnt 为初始连通分量数,在剩下的边数不小于 m - (n - cnt) 的时候 ...

  10. 阿牛的EOF牛肉串[HDU2047]

    阿牛的EOF牛肉串 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total S ...