数据库操作类mysql/mysqli/pdo

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

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

Java代码   收藏代码
  1. <?php  
  2. /** 
  3.  * 数据库操作类 
  4.  */  
  5. class Db  
  6. {  
  7.     protected $db;  
  8.     protected $_sql;  
  9.     protected $throw = 1//抛出sql语句错误信息  
  10.     protected $_query;  
  11.   
  12.     function __construct($dbname = NULL, $port = '3306') {  
  13.         if (!$dbname) {  
  14.             $this->db = new mysqli(HOST, USER, PASS, DBNAME, PORT);  
  15.         } else {  
  16.             $this->db = new mysqli(HOST, USER, PASS, $dbname, $port);  
  17.         }  
  18.   
  19.         $this->db->set_charset(CHARSET);  
  20.   
  21.         if ($this->db->connect_error) {  
  22.             if ($this->throw) {  
  23.                 throw new Exception($this->db->connect_error, $this->db->connect_errno);  
  24.             }  
  25.         }  
  26.   
  27.     }  
  28.   
  29.     /** 
  30.      * 查询字段 
  31.      * @param string $field 要查询的字段 
  32.      * @return Db 
  33.      */  
  34.     public function field($field) {  
  35.         $this->_query['field'] = "SELECT {$field}";  
  36.         return $this;  
  37.     }  
  38.   
  39.     /** 
  40.      * 查询的表名 
  41.      * @param string $table 要查询的表名可以带别名,例如table as tab 
  42.      * @return Db 
  43.      */  
  44.     public function table($table) {  
  45.         $this->_query['table'] = "FROM {$table}";  
  46.         return $this;  
  47.     }  
  48.   
  49.     /** 
  50.      * 联合查询 
  51.      * @param string $join 联合的表名可以带别名,必须加上关联的on语句 
  52.      * @return Db 
  53.      */  
  54.     public function join($join) {  
  55.         $this->_query['join'][] = $join;  
  56.         return $this;  
  57.     }  
  58.   
  59.     /** 
  60.      * 条件语句 
  61.      * @param string $where sql条件语句不需加where关键字 
  62.      * @return Db 
  63.      */  
  64.     public function where($where) {  
  65.         $this->_query['where'] = "WHERE {$where}";  
  66.         return $this;  
  67.     }  
  68.   
  69.     /** 
  70.      * 排序 
  71.      * @param string $order 
  72.      * @return Db 
  73.      */  
  74.     public function order($order) {  
  75.         if ($order != '') {  
  76.             $this->_query['order'] = "ORDER BY {$order}";  
  77.         }  
  78.         return $this;  
  79.     }  
  80.   
  81.     /** 
  82.      * 获取条数 
  83.      * @param string $limit 格式0,5 
  84.      * @return Db 
  85.      */  
  86.     public function limit($limit) {  
  87.         if ($limit != '') {  
  88.             $this->_query['limit'] = "LIMIT {$limit}";  
  89.         }  
  90.         return $this;  
  91.     }  
  92.   
  93.     /** 
  94.      * 构造sql语句 
  95.      * @return string 返回sql语句 
  96.      */  
  97.     private function buildsql() {  
  98.   
  99.         $sql = $this->_query['field'] . ' ' . $this->_query['table'];  
  100.   
  101.         if (!empty($this->_query['join'])) {  
  102.             foreach ($this->_query['join'] as $join) {  
  103.                 $sql .= " {$join}";  
  104.             };  
  105.         }  
  106.   
  107.         if (isset($this->_query['del'])) {  
  108.             $sql = $this->_query['del'] . ' ' . $this->_query['table'];  
  109.         }  
  110.   
  111.         if ($this->_query['where'] != '') {  
  112.             $sql .= ' ' . $this->_query['where'];  
  113.         }  
  114.   
  115.         if (isset($this->_query['order']) && $this->_query['order'] != '') {  
  116.             $sql .= ' ' . $this->_query['order'];  
  117.         }  
  118.         unset($this->_query);  
  119.   
  120.         return $sql;  
  121.   
  122.     }  
  123.   
  124.     /** 
  125.      * 执行select查询 
  126.      * @return bool|array    失败返回FALSE,成功返回二维数组 
  127.      */  
  128.     public function select() {  
  129.         $sql = $this->buildsql();  
  130.   
  131.         return $this->fetchAll($sql);  
  132.     }  
  133.   
  134.     /** 
  135.      * 获取所有记录数 
  136.      * 
  137.      * @return int            返回所有记录数 
  138.      */  
  139.     public function findNumRows() {  
  140.         $sql = $this->buildsql();  
  141.   
  142.         $res = $this->query($sql);  
  143.   
  144.         return $res->num_rows;  
  145.     }  
  146.   
  147.     /** 
  148.      * 删除一行记录 
  149.      * @return boolean 
  150.      */  
  151.     public function delRow() {  
  152.         $this->_query['del'] = "DELETE";  
  153.   
  154.         $sql = $this->buildsql();  
  155.   
  156.         $res = $this->query($sql);  
  157.   
  158.         if ($res === FALSE) {  
  159.             return FALSE;  
  160.         }  
  161.   
  162.         return TRUE;  
  163.     }  
  164.   
  165.     /** 
  166.      * 检查唯一性 
  167.      * 
  168.      * @param string $table 表名 
  169.      * @param string $where 查询条件 
  170.      * @param string $keyid 自动id 
  171.      * @return boolean            存在返回FALSE,否则返回TRUE 
  172.      */  
  173.     public function chkUnique($table, $where, $keyid = 'id') {  
  174.   
  175.         $sql = "SELECT {$keyid} from {$table} WHERE {$where}";  
  176.   
  177.         $num = $this->getNumRows($sql);  
  178.   
  179.         if ($num > 0) {  
  180.             return FALSE;  
  181.         }  
  182.   
  183.         return TRUE;  
  184.     }  
  185.   
  186.     /** 
  187.      * 执行select查询 
  188.      * @return bool|array    失败返回FALSE,成功返回一维数组 
  189.      */  
  190.     public function findRow() {  
  191.         $sql = $this->buildsql();  
  192.   
  193.         return $this->fetchRow($sql);  
  194.     }  
  195.   
  196.     /** 
  197.      * 执行sql语句查询 
  198.      * @param string $sql sql语句 
  199.      * @return mixed 返回资源结果集或布尔值 
  200.      */  
  201.     public function query($sql) {  
  202.         $this->_sql = $sql;  
  203.         $res = $this->db->query($sql);  
  204.   
  205.         if ($res === FALSE) {  
  206.             if ($this->throw) {  
  207.                 throw new Exception("发生错误: 错误信息  {$this->getLastErr()} 相关sql语句 {$this->_sql}", $this->db->errno);  
  208.             } else {  
  209.                 return FALSE;  
  210.             }  
  211.         }  
  212.   
  213.         return $res;  
  214.     }  
  215.   
  216.     /** 
  217.      * 设置是否抛出sql异常 
  218.      * @param bool $bool 
  219.      */  
  220.     public function setThrow($bool = FALSE) {  
  221.         $this->throw = $bool;  
  222.     }  
  223.   
  224.     /** 
  225.      * 执行sql脚本从文件 
  226.      * @param file $sqlfile sql脚本文件路径 
  227.      * @return boolean 
  228.      */  
  229.     public function buildSqlfile($sqlfile) {  
  230.         $file = file($sqlfile);  
  231.   
  232.         if ($file === FALSE || empty($file)) {  
  233.             return FALSE;  
  234.         }  
  235.   
  236.         foreach ($file as $key => $val) {  
  237.             if (preg_match('/^(-|#)/', $val) || trim($val) == '') {  
  238.                 continue;  
  239.             }  
  240.   
  241.             $new[] = $val;  
  242.         }  
  243.   
  244.         $sqls = split(';', join('', $new));  
  245.   
  246.   
  247.         foreach ($sqls as $sql) {  
  248.             $this->query($sql);  
  249.         }  
  250.   
  251.         return TRUE;  
  252.     }  
  253.   
  254.     /** 
  255.      * 获取一条数据 
  256.      * @param string $sql sql语句 
  257.      * @return array 一维数组 
  258.      */  
  259.     public function fetchRow($sql) {  
  260.         $res = $this->query($sql);  
  261.         $result = @$res->fetch_assoc();  
  262.         return $result;  
  263.     }  
  264.   
  265.     /** 
  266.      * 获取多条数据 
  267.      * @param string $sql 
  268.      * @return array 二维数组 
  269.      */  
  270.     public function fetchAll($sql, $key = '') {  
  271.         $res = $this->query($sql);  
  272.   
  273.         $result = array();  
  274.   
  275.         while ($row = $res->fetch_assoc()) {  
  276.             if ($key) {  
  277.                 $result [$row[$key]] = $row;  
  278.             } else {  
  279.                 $result [] = $row;  
  280.             }  
  281.         }  
  282.   
  283.         return $result;  
  284.     }  
  285.   
  286.     /** 
  287.      * 获取所有记录数 
  288.      * 
  289.      * @param string $sql sql语句 
  290.      * @return int            返回所有记录数 
  291.      */  
  292.     public function getNumRows($sql) {  
  293.         $res = $this->query($sql);  
  294.   
  295.         return $res->num_rows;  
  296.     }  
  297.   
  298.     /** 
  299.      * 返回最后查询自动生成的id 
  300.      */  
  301.     public function getLastId() {  
  302.         return $this->db->insert_id;  
  303.     }  
  304.   
  305.     /** 
  306.      * 返回最后查询出现的错误信息 
  307.      */  
  308.     public function getLastErr() {  
  309.         return $this->db->error;  
  310.     }  
  311.   
  312.     /** 
  313.      * 获取最后一次执行的sql语句 
  314.      * 
  315.      * @return string sql 
  316.      */  
  317.     public function getLastSql() {  
  318.         return $this->_sql;  
  319.     }  
  320.   
  321.     /** 
  322.      * 锁定表 
  323.      * @param string $tabname 表名 
  324.      * @param string $mode 模式 
  325.      */  
  326.     public function locktab($tabname, $mode = 'READ') {  
  327.         $this->query("LOCK TABLE {$tabname} {$mode}");  
  328.         return $this;  
  329.     }  
  330.   
  331.     /** 
  332.      * 解锁表 
  333.      */  
  334.     public function unlocktab() {  
  335.         $this->query("UNLOCK TABLES");  
  336.     }  
  337.   
  338.     /** 
  339.      * 执行锁定查询 
  340.      */  
  341.     public function execlockquery() {  
  342.         $sql = $this->buildsql();  
  343.   
  344.     }  
  345.   
  346.     /** 
  347.      * 执行添加记录操作 
  348.      * @param $data        要增加的数据,参数为数组。数组key为字段值,数组值为数据取值 格式:array('字段名' => 值); 
  349.      * @param $table        数据表 
  350.      * @return boolean 
  351.      */  
  352.     public function add($data, $table, $replace = false) {  
  353.         if (!is_array($data) || $table == '' || count($data) == 0) {  
  354.             return false;  
  355.         }  
  356.         $fields = $values = array();  
  357.         //遍历记录, 格式化字段名称与值  
  358.         foreach($data as $key => $val)  
  359.         {  
  360.             $fields[] = "`{$table}`.`{$key}`";  
  361.             $values[] = is_numeric($val) ? $val : "'{$val}'";  
  362.         }  
  363.         $field = join(',', $fields);  
  364.         $value = join(',', $values);  
  365.         unset($fields, $values);  
  366.   
  367.   
  368.         $cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';  
  369.         $sql = $cmd . ' `' . $table . '`(' . $field . ') VALUES (' . $value . ')';  
  370.         $this->query($sql);  
  371.           
  372.         return $this->getLastId();  
  373.     }  
  374.   
  375.     /** 
  376.      * 执行更新记录操作 
  377.      * @param $table        数据表 
  378.      * @param $data        要更新的数据内容,参数可以为数组也可以为字符串,建议数组。 
  379.      *      为数组时数组key为字段值,数组值为数据取值 
  380.      *      为字符串时[例:`name`='phpcms',`hits`=`hits`+1]。 
  381.      *      为数组时[例: array('name'=>'phpcms','password'=>'123456')] 
  382.      *      数组可使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1 
  383.      * 
  384.      * @param $where        更新数据时的条件 
  385.      * @return boolean 
  386.      */  
  387.     public function update($table, $data, $where = '') {  
  388.         if ($table == '' or $where == '') {  
  389.             return false;  
  390.         }  
  391.   
  392.         $where = ' WHERE ' . $where;  
  393.         $field = '';  
  394.         if (is_string($data) && $data != '') {  
  395.             $field = $data;  
  396.         } elseif (is_array($data) && count($data) > 0) {  
  397.             $fields = array();  
  398.             foreach ($data as $k => $v) {  
  399.                 switch (substr($v, 02)) {  
  400.                     case '+=':  
  401.                         $v = substr($v, 2);  
  402.                         if (is_numeric($v)) {  
  403.                             $fields[] =  "`{$k}`=`{$k}` + $v";  
  404.                         } else {  
  405.                             continue;  
  406.                         }  
  407.   
  408.                         break;  
  409.                     case '-=':  
  410.                         $v = substr($v, 2);  
  411.                         if (is_numeric($v)) {  
  412.                             $fields[] =  "`{$k}`=`{$k}` - $v";  
  413.                         } else {  
  414.                             continue;  
  415.                         }  
  416.                         break;  
  417.                     default:  
  418.                         $fields[] =  "`{$k}`= $v";  
  419.                 }  
  420.             }  
  421.             $field = implode(',', $fields);  
  422.         } else {  
  423.             return false;  
  424.         }  
  425.   
  426.         $sql = 'UPDATE `' . $table . '` SET ' . $field . $where;  
  427.         return $this->query($sql);  
  428.     }  
  429.   
  430.     /** 
  431.      * 执行删除记录操作 
  432.      * @param $table        数据表 
  433.      * @param $where        删除数据条件,不充许为空。 
  434.      *                        如果要清空表,使用empty方法 
  435.      * @return boolean 
  436.      */  
  437.     public function delete($table, $where = null) {  
  438.         if ($table == '') {  
  439.             return false;  
  440.         }  
  441.   
  442.         $sql = 'DELETE FROM `' . $table . '`';  
  443.         if ($where) {  
  444.             $sql .= " WHERE {$where}";  
  445.         }  
  446.   
  447.         return $this->query($sql);  
  448.     }  
  449.   
  450.     /** 
  451.      * 自动提交 
  452.      * @param BOOL $status 默认false关闭自动提交,设置为true时打开自动提交 
  453.      */  
  454.     public function autocommit($status = FALSE) {  
  455.         $this->db->autocommit($status);  
  456.     }  
  457.   
  458.     /** 
  459.      * 提交事务 
  460.      */  
  461.     public function commit() {  
  462.         $this->db->commit();  
  463.     }  
  464.   
  465.     /** 
  466.      * 回滚事务 
  467.      */  
  468.     public function rollback() {  
  469.         $this->db->rollback();  
  470.     }  
  471.   
  472.   
  473.     public function __destruct() {  
  474.         $this->db->close();  
  475.     }  
  476.   
  477. }  
 
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
6天前
|
关系型数据库 MySQL 分布式数据库
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
《MySQL 简易速速上手小册》第6章:MySQL 复制和分布式数据库(2024 最新版)
37 2
|
22天前
|
SQL 数据可视化 关系型数据库
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
105 0
|
3天前
|
SQL 存储 关系型数据库
数据库开发之mysql前言以及详细解析
数据库开发之mysql前言以及详细解析
14 0
|
18天前
|
存储 关系型数据库 MySQL
MySQL基础入门:数据库操作全攻略
MySQL基础入门:数据库操作全攻略
48 0
|
18天前
|
关系型数据库 MySQL 数据库
卸载云服务器上的 MySQL 数据库
卸载云服务器上的 MySQL 数据库
33 0
|
8天前
|
SQL 关系型数据库 MySQL
MySQL环境搭建——“MySQL数据库”
MySQL环境搭建——“MySQL数据库”
|
8天前
|
SQL NoSQL 关系型数据库
初识MySQL数据库——“MySQL数据库”
初识MySQL数据库——“MySQL数据库”
|
10天前
|
关系型数据库 MySQL 数据库
数据库基础(mysql)
数据库基础(mysql)
|
10天前
|
SQL 关系型数据库 数据库
【后端面经】【数据库与MySQL】SQL优化:如何发现SQL中的问题?
【4月更文挑战第12天】数据库优化涉及硬件升级、操作系统调整、服务器/引擎优化和SQL优化。SQL优化目标是减少磁盘IO和内存/CPU消耗。`EXPLAIN`命令用于检查SQL执行计划,关注`type`、`possible_keys`、`key`、`rows`和`filtered`字段。设计索引时考虑外键、频繁出现在`where`、`order by`和关联查询中的列,以及区分度高的列。大数据表改结构需谨慎,可能需要停机、低峰期变更或新建表。面试中应准备SQL优化案例,如覆盖索引、优化`order by`、`count`和索引提示。优化分页查询时避免大偏移量,可利用上一批的最大ID进行限制。
37 3
|
11天前
|
存储 关系型数据库 MySQL
【后端面经】【数据库与MySQL】为什么MySQL用B+树而不用B树?-02
【4月更文挑战第11天】数据库索引使用规则:`AND`用`OR`不用,正用反不用,范围中断。索引带来空间和内存代价,包括额外磁盘空间、内存占用和数据修改时的维护成本。面试中可能涉及B+树、聚簇索引、覆盖索引等知识点。MySQL采用B+树,因其利于范围查询和内存效率。数据库不使用索引可能因`!=`、`LIKE`、字段区分度低、特殊表达式或全表扫描更快。索引与NULL值处理在不同数据库中有差异,MySQL允许NULL在索引中的使用。
17 3