数据库操作类mysql/mysqli/pdo

PDO,MYSQL,MYSQLI的各自不同介绍,PDO,MYSQL,MYSQLI 性能哪个比较好

普通的mysql连接肯定是会被抛弃的 因为每次都要防止sql注入的问题 而且相对来说比较慢

首先, mysqli 连接是永久连接,而mysql是非永久连接 。什么意思呢? mysql连接每当第二次使用的时候,都会重新打开一个新的进程,而mysqli则只使用同一个进程,这样可以很大程度的减轻服务器端压力。
mysqli是在普通mysql的基础上做的一次优化说实话很成功 预处理方式完全解决了sql注入的问题
但是唯一的不足点 就是只支持mysql数据库当然如果你要是不操作其他的数据库或者 当然这无疑是最好的选择
PDO则是最新出来的一种 连接方式 兼容大部分数据库 也解决了sql注入 但是也有缺点 它只支持php5.1以上的版本 不过听说在未来的php6中 只支持这种连接.PDO统一所有数据库抽象层对象接口,mysqli只统一mysql的

简单说,PDO可以实现同样的代码对不同数据库的操作,例如你从mysql迁移到mssql,程序基本不需要改动
而mysqli简单理解未mysql的封装就好 在高负载的情况下.PDO开启长连接能够得到一个相对稳定的负载“值”。但是效率却不是最高的。 mysql最快。mysqli其次。只是mysql和mysqli在高并发、系统高负载的时候。其所承担的负载也是很可观的。PDO则不会。http://hudeyong926.iteye.com/blog/1824869

<?php

/**
 * 数据库操作类
 */
class Db
{
    protected $db;
    protected $_sql;
    protected $throw = 1; //抛出sql语句错误信息
    protected $_query;

    function __construct($dbname = NULL, $port = '3306')
    {
        if (!$dbname) {
            $this->db = new mysqli(HOST, USER, PASS, DBNAME, PORT);
        } else {
            $this->db = new mysqli(HOST, USER, PASS, $dbname, $port);
        }

        $this->db->set_charset(CHARSET);

        if ($this->db->connect_error) {
            if ($this->throw) {
                throw new Exception($this->db->connect_error, $this->db->connect_errno);
            }
        }

    }

    /**
     * 查询字段
     * @param string $field 要查询的字段
     * @return Db
     */
    public function field($field)
    {
        $this->_query['field'] = "SELECT {$field}";
        return $this;
    }

    /**
     * 查询的表名
     * @param string $table 要查询的表名可以带别名,例如table as tab
     * @return Db
     */
    public function table($table)
    {
        $this->_query['table'] = "FROM {$table}";
        return $this;
    }

    /**
     * 联合查询
     * @param string $join 联合的表名可以带别名,必须加上关联的on语句
     * @return Db
     */
    public function join($join)
    {
        $this->_query['join'][] = $join;
        return $this;
    }

    /**
     * 条件语句
     * @param string $where sql条件语句不需加where关键字
     * @return Db
     */
    public function where($where)
    {
        $this->_query['where'] = "WHERE {$where}";
        return $this;
    }

    /**
     * 排序
     * @param string $order
     * @return Db
     */
    public function order($order)
    {
        if ($order != '') {
            $this->_query['order'] = "ORDER BY {$order}";
        }
        return $this;
    }

    /**
     * 获取条数
     * @param string $limit 格式0,5
     * @return Db
     */
    public function limit($limit)
    {
        if ($limit != '') {
            $this->_query['limit'] = "LIMIT {$limit}";
        }
        return $this;
    }

    /**
     * 构造sql语句
     * @return string 返回sql语句
     */
    private function buildsql()
    {

        $sql = $this->_query['field'] . ' ' . $this->_query['table'];

        if (!empty($this->_query['join'])) {
            foreach ($this->_query['join'] as $join) {
                $sql .= " {$join}";
            };
        }

        if (isset($this->_query['del'])) {
            $sql = $this->_query['del'] . ' ' . $this->_query['table'];
        }

        if (isset($this->_query['where']) && $this->_query['where'] != '') {
            $sql .= ' ' . $this->_query['where'];
        }

        if (isset($this->_query['limit']) && $this->_query['limit'] != '') {
            $sql .= ' ' . $this->_query['limit'];
        }
        if (isset($this->_query['order']) && $this->_query['order'] != '') {
            $sql .= ' ' . $this->_query['order'];
        }
        unset($this->_query);

        return $sql;

    }

    /**
     * 执行select查询
     * @return bool|array    失败返回FALSE,成功返回二维数组
     */
    public function select()
    {
        $sql = $this->buildsql();

        return $this->fetchAll($sql);
    }

    /**
     * 获取所有记录数
     *
     * @return int            返回所有记录数
     */
    public function findNumRows()
    {
        $sql = $this->buildsql();

        $res = $this->query($sql);

        return $res->num_rows;
    }

    /**
     * 删除一行记录
     * @return boolean
     */
    public function delRow()
    {
        $this->_query['del'] = "DELETE";

        $sql = $this->buildsql();

        $res = $this->query($sql);

        if ($res === FALSE) {
            return FALSE;
        }

        return TRUE;
    }

    /**
     * 检查唯一性
     *
     * @param string $table 表名
     * @param string $where 查询条件
     * @param string $keyid 自动id
     * @return boolean            存在返回FALSE,否则返回TRUE
     */
    public function chkUnique($table, $where, $keyid = 'id')
    {

        $sql = "SELECT {$keyid} from {$table} WHERE {$where}";

        $num = $this->getNumRows($sql);

        if ($num > 0) {
            return FALSE;
        }

        return TRUE;
    }

    /**
     * 执行select查询
     * @return bool|array    失败返回FALSE,成功返回一维数组
     */
    public function findRow()
    {
        $sql = $this->buildsql();

        return $this->fetchRow($sql);
    }
    /**
     * 执行select查询
     * @return bool|array    失败返回FALSE,成功返回一维数组
     */
    public function findOne()
    {
        $sql = $this->buildsql();

        return $this->fetchOne($sql);
    }

    /**
     * 获取一条数据
     * @param string $sql sql语句
     * @return array 一维数组
     */
    public function fetchOne($sql)
    {
        $res = $this->fetchRow($sql);
        if ($res) {
            $field = key($res);
            $res = $res[$field];
        }
        return $res;
    }
    /**
     * 执行sql语句查询
     * @param string $sql sql语句
     * @return mixed 返回资源结果集或布尔值
     */
    public function query($sql)
    {
        $this->_sql = $sql;
        $res = $this->db->query($sql);

        if ($res === FALSE) {
            if ($this->throw) {
                throw new Exception("发生错误: 错误信息  {$this->getLastErr()} 相关sql语句 {$this->_sql}", $this->db->errno);
            } else {
                return FALSE;
            }
        }

        return $res;
    }

    /**
     * 设置是否抛出sql异常
     * @param bool $bool
     */
    public function setThrow($bool = FALSE)
    {
        $this->throw = $bool;
    }

    /**
     * 执行sql脚本从文件
     * @param file $sqlfile sql脚本文件路径
     * @return boolean
     */
    public function buildSqlfile($sqlfile)
    {
        $file = file($sqlfile);

        if ($file === FALSE || empty($file)) {
            return FALSE;
        }

        foreach ($file as $key => $val) {
            if (preg_match('/^(-|#)/', $val) || trim($val) == '') {
                continue;
            }

            $new[] = $val;
        }

        $sqls = split(';', join('', $new));


        foreach ($sqls as $sql) {
            $this->query($sql);
        }

        return TRUE;
    }

    /**
     * 获取一条数据
     * @param string $sql sql语句
     * @return array 一维数组
     */
    public function fetchRow($sql)
    {
        $res = $this->query($sql);
        $result = @$res->fetch_assoc();
        return $result;
    }

    /**
     * 获取多条数据
     * @param string $sql
     * @return array 二维数组
     */
    public function fetchAll($sql, $key = '')
    {
        $res = $this->query($sql);

        $result = array();

        while ($row = $res->fetch_assoc()) {
            if ($key) {
                $result [$row[$key]] = $row;
            } else {
                $result [] = $row;
            }
        }

        return $result;
    }

    /**
     * 获取所有记录数
     *
     * @param string $sql sql语句
     * @return int            返回所有记录数
     */
    public function getNumRows($sql)
    {
        $res = $this->query($sql);

        return $res->num_rows;
    }

    /**
     * 返回最后查询自动生成的id
     */
    public function getLastId()
    {
        return $this->db->insert_id;
    }

    /**
     * 返回最后查询出现的错误信息
     */
    public function getLastErr()
    {
        return $this->db->error;
    }

    /**
     * 获取最后一次执行的sql语句
     *
     * @return string sql
     */
    public function getLastSql()
    {
        return $this->_sql;
    }

    /**
     * 锁定表
     * @param string $tabname 表名
     * @param string $mode 模式
     */
    public function locktab($tabname, $mode = 'READ')
    {
        $this->query("LOCK TABLE {$tabname} {$mode}");
        return $this;
    }

    /**
     * 解锁表
     */
    public function unlocktab()
    {
        $this->query("UNLOCK TABLES");
    }

    /**
     * 执行锁定查询
     */
    public function execlockquery()
    {
        $sql = $this->buildsql();

    }

    /**
     * 执行添加记录操作
     * @param $data        要增加的数据,参数为数组。数组key为字段值,数组值为数据取值 格式:array('字段名' => 值);
     * @param $table        数据表
     * @return boolean
     */
    public function add($data, $table, $replace = false)
    {
        if (!is_array($data) || $table == '' || count($data) == 0) {
            return false;
        }

        $fielddata = array_keys($data);
        $valuedata = array_values($data);
        array_walk($fielddata, array($this, 'add_special_char'));
        array_walk($valuedata, array($this, 'escape_string'));

        $field = implode(',', $fielddata);
        $value = implode(',', $valuedata);


        $cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
        $sql = $cmd . ' `' . $table . '`(' . $field . ') VALUES (' . $value . ')';
        $this->query($sql);

        return $this->getLastId();
    }

    /**
     * 执行更新记录操作
     * @param $table        数据表
     * @param $data        要更新的数据内容,参数可以为数组也可以为字符串,建议数组。
     *      为数组时数组key为字段值,数组值为数据取值
     *      为字符串时[例:`name`='phpcms',`hits`=`hits`+1]。
     *      为数组时[例: array('name'=>'phpcms','password'=>'123456')]
     *      数组可使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
     *
     * @param $where        更新数据时的条件
     * @return boolean
     */
    public function update($table, $data, $where = '')
    {
        if ($table == '' or $where == '') {
            return false;
        }

        $where = ' WHERE ' . $where;
        $field = '';
        if (is_string($data) && $data != '') {
            $field = $data;
        } elseif (is_array($data) && count($data) > 0) {
            $fields = array();
            foreach ($data as $k => $v) {
                switch (substr($v, 0, 2)) {
                    case '+=':
                        $v = substr($v, 2);
                        if (is_numeric($v)) {
                            $fields[] = $this->add_special_char($k) . '=' . $this->add_special_char($k) . '+' . $this->escape_string($v, '', false);
                        } else {
                            continue;
                        }

                        break;
                    case '-=':
                        $v = substr($v, 2);
                        if (is_numeric($v)) {
                            $fields[] = $this->add_special_char($k) . '=' . $this->add_special_char($k) . '-' . $this->escape_string($v, '', false);
                        } else {
                            continue;
                        }
                        break;
                    default:
                        $fields[] = $this->add_special_char($k) . '=' . $this->escape_string($v);
                }
            }
            $field = implode(',', $fields);
        } else {
            return false;
        }

        $sql = 'UPDATE `' . $table . '` SET ' . $field . $where;
        return $this->query($sql);
    }

    /**
     * 执行删除记录操作
     * @param $table        数据表
     * @param $where        删除数据条件,不充许为空。
     *                        如果要清空表,使用empty方法
     * @return boolean
     */
    public function delete($table, $where = null)
    {
        if ($table == '') {
            return false;
        }

        $sql = 'DELETE FROM `' . $table . '`';
        if ($where) {
            $sql .= " WHERE {$where}";
        }

        return $this->query($sql);
    }

    /**
     * 自动提交
     * @param BOOL $status 默认false关闭自动提交,设置为true时打开自动提交
     */
    public function autocommit($status = FALSE)
    {
        $this->db->autocommit($status);
    }

    /**
     * 提交事务
     */
    public function commit()
    {
        $this->db->commit();
    }

    /**
     * 回滚事务
     */
    public function rollback()
    {
        $this->db->rollback();
    }

    /**
     * 对字段两边加反引号,以保证数据库安全
     * @param $value 数组值
     */
    public function add_special_char(&$value)
    {
        if ('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos($value, '`')) {
            //不处理包含* 或者 使用了sql方法。
        } else {
            $value = '`' . trim($value) . '`';
        }
        if (preg_match("/\b(select|insert|update|delete)\b/i", $value)) {
            $value = preg_replace("/\b(select|insert|update|delete)\b/i", '', $value);
        }
        return $value;
    }

    /**
     * 对字段值两边加引号,以保证数据库安全
     * @param $value 数组值
     * @param $key 数组key
     * @param $quotation
     */
    public function escape_string(&$value, $key = '', $quotation = 1)
    {
        if ($quotation) {
            $q = '\'';
        } else {
            $q = '';
        }
        $value = $q . $value . $q;
        return $value;
    }
    
    public function __destruct()
    {
        $this->db->close();
    }

}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值