天天看点

数据库操作类mysql/mysqli/pdo

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

首先, mysqli 连接是永久连接,而mysql是非永久连接 。什么意思呢? mysql连接每当第二次使用的时候,都会重新打开一个新的进程,而mysqli则只使用同一个进程,这样可以很大程度的减轻服务器端压力。

mysqli是在普通mysql的基础上做的一次优化说实话很成功 预处理方式完全解决了sql注入的问题 

pdo则是最新出来的一种 连接方式 兼容大部分数据库 也解决了sql注入 但是也有缺点 它只支持php5.1以上的版本不过听说在未来的php6中 只支持这种连接.pdo统一所有数据库抽象层对象接口,mysqli只统一mysql的 

简单说,pdo可以实现同样的代码对不同数据库的操作,例如你从mysql迁移到mssql,程序基本不需要改动 

数据库操作类mysql/mysqli/pdo

<?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 

    public function table($table) {  

        $this->_query['table'] = "from {$table}";  

     * 联合查询 

     * @param string $join 联合的表名可以带别名,必须加上关联的on语句 

    public function join($join) {  

        $this->_query['join'][] = $join;  

     * 条件语句 

     * @param string $where sql条件语句不需加where关键字 

    public function where($where) {  

        $this->_query['where'] = "where {$where}";  

     * 排序 

     * @param string $order 

    public function order($order) {  

        if ($order != '') {  

            $this->_query['order'] = "order by {$order}";  

     * 获取条数 

     * @param string $limit 格式0,5 

    public function limit($limit) {  

        if ($limit != '') {  

            $this->_query['limit'] = "limit {$limit}";  

     * 构造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 ($this->_query['where'] != '') {  

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

        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() {  

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

        return $res->num_rows;  

     * 删除一行记录 

     * @return boolean 

    public function delrow() {  

        $this->_query['del'] = "delete";  

        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 bool|array    失败返回false,成功返回一维数组 

    public function findrow() {  

        return $this->fetchrow($sql);  

     * 执行sql语句查询 

     * @param string $sql sql语句 

     * @return mixed 返回资源结果集或布尔值 

    public function query($sql) {  

        $this->_sql = $sql;  

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

                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脚本文件路径 

    public function buildsqlfile($sqlfile) {  

        $file = file($sqlfile);  

        if ($file === false || empty($file)) {  

        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 array 一维数组 

    public function fetchrow($sql) {  

        $result = @$res->fetch_assoc();  

        return $result;  

     * 获取多条数据 

     * @param string $sql 

     * @return array 二维数组 

    public function fetchall($sql, $key = '') {  

        $result = array();  

        while ($row = $res->fetch_assoc()) {  

            if ($key) {  

                $result [$row[$key]] = $row;  

                $result [] = $row;  

    public function getnumrows($sql) {  

     * 返回最后查询自动生成的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}");  

     * 解锁表 

    public function unlocktab() {  

        $this->query("unlock tables");  

     * 执行锁定查询 

    public function execlockquery() {  

     * 执行添加记录操作 

     * @param $data        要增加的数据,参数为数组。数组key为字段值,数组值为数据取值 格式:array('字段名' => 值); 

     * @param $table        数据表 

    public function add($data, $table, $replace = false) {  

        if (!is_array($data) || $table == '' || count($data) == 0) {  

        $fields = $values = array();  

        //遍历记录, 格式化字段名称与值  

        foreach($data as $key => $val)  

        {  

            $fields[] = "`{$table}`.`{$key}`";  

            $values[] = is_numeric($val) ? $val : "'{$val}'";  

        $field = join(',', $fields);  

        $value = join(',', $values);  

        unset($fields, $values);  

        $cmd = $replace ? 'replace into' : 'insert into';  

        $sql = $cmd . ' `' . $table . '`(' . $field . ') values (' . $value . ')';  

        $this->query($sql);  

        return $this->getlastid();  

     * 执行更新记录操作 

     * @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        更新数据时的条件 

    public function update($table, $data, $where = '') {  

        if ($table == '' or $where == '') {  

        $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[] =  "`{$k}`=`{$k}` + $v";  

                        } else {  

                            continue;  

                        }  

                        break;  

                    case '-=':  

                            $fields[] =  "`{$k}`=`{$k}` - $v";  

                    default:  

                        $fields[] =  "`{$k}`= $v";  

                }  

            $field = implode(',', $fields);  

        $sql = 'update `' . $table . '` set ' . $field . $where;  

        return $this->query($sql);  

     * 执行删除记录操作 

     * @param $where        删除数据条件,不充许为空。 

     *                        如果要清空表,使用empty方法 

    public function delete($table, $where = null) {  

        if ($table == '') {  

        $sql = 'delete from `' . $table . '`';  

        if ($where) {  

            $sql .= " where {$where}";  

     * 自动提交 

     * @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();  

    public function __destruct() {  

        $this->db->close();  

}