赞
踩
php操作mysql数据库,大家都知道有三种驱动,mysql mysqli pdo,其中mysql在php7之后被废除了。不是本文重点。咱现在来分析一下mysqli和PDO的区别,下面一张表用来说明他们的区别
PDO | Mysqli | |
数据库类型支持 | 很多 | 仅支持mysql |
API | OOP | OOP+面向过程 |
命名参数 | 支持 | 不支持 |
连接 | 容易 | 容易 |
对象映射 | 支持 | 支持 |
- // PDO
- $pdo = new PDO("mysql:host=localhost;dbname=database", 'username', 'password');
-
- // mysqli面向过程
- $mysqli = mysqli_connect('localhost','username','password','database');
-
- // mysqli面向对象
- $mysqli = new mysqli('localhost','username','password','database');
pdo多种支持
代码表现
var_dump(PDO::getAvailableDrivers());
mysqli 单一
POD方式
- $params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);
-
- $pdo->prepare('
- SELECT * FROM users
- WHERE username = :username
- AND email = :email
- AND last_login > :last_login');
-
- $pdo->execute($params);
mysqli方式
- $query = $mysqli->prepare('
- SELECT * FROM users
- WHERE username = ?
- AND email = ?
- AND last_login > ?');
-
- $query->bind_param('sss', 'test', $mail, time() - 3600);
- $query->execute();
假设我们有一个类,是如下这样
- class User {
- public $id;
- public $first_name;
- public $last_name;
-
- public function info()
- {
- return '#'.$this->id.': '.$this->first_name.' '.$this->last_name;
- }
- }
看看2者的方式
- $query = "SELECT id, first_name, last_name FROM users";
-
- // PDO
- $result = $pdo->query($query);
- $result->setFetchMode(PDO::FETCH_CLASS, 'User');
-
- while ($user = $result->fetch()) {
- echo $user->info()."\n";
- }
- // MySQLI, procedural way
- if ($result = mysqli_query($mysqli, $query)) {
- while ($user = mysqli_fetch_object($result, 'User')) {
- echo $user->info()."\n";
- }
- }
- // MySQLi, object oriented way
- if ($result = $mysqli->query($query)) {
- while ($user = $result->fetch_object('User')) {
- echo $user->info()."\n";
- }
- }
二者都可以防止sql注入
看下代码
- // PDO, "manual" escaping
- $username = PDO::quote($_GET['username']);
-
- $pdo->query("SELECT * FROM users WHERE username = $username");
-
- // mysqli, "manual" escaping
- $username = mysqli_real_escape_string($_GET['username']);
-
- $mysqli->query("SELECT * FROM users WHERE username = '$username'");
- // PDO, prepared statement
- $pdo->prepare('SELECT * FROM users WHERE username = :username');
- $pdo->execute(array(':username' => $_GET['username']));
-
- // mysqli, prepared statements
- $query = $mysqli->prepare('SELECT * FROM users WHERE username = ?');
- $query->bind_param('s', $_GET['username']);
- $query->execute();
推荐大家用pdo,因为pdo的强大之处是显而易见的,支持多种数据库,还有参数绑定是特色。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。