<?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. 查看APP用到的图片方法

    把APP对应的APK文件下载到电脑上,然后把扩展名修改为zip,然后进行解压,就可以看了.

  2. js:数据结构笔记1---数组

    JS中数组: 只是一种特殊的对象,比其他语言中效率低: 属性是用来表示偏移量的索引:在JS中,数字索引在内部被转化为字符串类型(这也是为什么写对象属性的时候可以不叫引号),因为对象中的属性必须是字符串 ...

  3. HDU3501 Calculation 2(欧拉函数)

    题目求小于n不与n互质的正整数的和. 一个结论是小于n与n互质的正整数和=φ(n)*n/2. 因为如果a与n互质,那么n-a也与n互质,即若gcd(a,n)=1则gcd(n-a,n)=1,反证法即可证 ...

  4. A C[HDU1570]

    A C Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...

  5. BZOJ1092 : [SCOI2003]蜘蛛难题

    按时间一步一步模拟. 每一次,首先将所有没有水但是可以被灌到水的管子标记为有水,然后求出有水的管子里水面高度的最小值. 如果$a$号管有水且最小值为$b$,那么说明此时蜘蛛碰到了水. 如果有管子溢出且 ...

  6. BZOJ4123 : [Baltic2015]Hacker

    黑掉的一定是一个长度为$\lfloor\frac{n+1}{2}\rfloor$的区间. 于是枚举初始点,然后查询包含它的区间的最小值. 通过维护前后缀最小值+单调队列$O(n)$解决. #inclu ...

  7. Hook to function

    myFun.h 1: #include <stdio.h> 2:  3: void __cyg_profile_func_enter(void *this_fn, void *call_s ...

  8. JS正则表达式验证数字(很全)

    1.<script type="text/javascript"> 2.     function validate(){ 3.       var reg = new ...

  9. TYVJ P1077 有理逼近 Label:坑,tle的好帮手 不懂

    描述 对于一个素数P,我们可以用一系列有理分数(分子.分母都是不大于N的自然数)来逼近sqrt(p),例如P=2,N=5的时候:1/1<5/4<4/3<sqrt(2)<3/2& ...

  10. 运用正则表达式在Asp中过滤Html标签代码的四种不同方法

    Function RemoveHTML(strHTML)Dim objregExp, Match, MatchesSet objRegExp = New RegexpobjRegExp.IgnoreC ...