mysqli和PDO的区别,下面一张表用来说明他们的区别
PDO | Musqli | |
数据库类型支持 | 很多类型,如mysql、pgsql等 | 只支持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());
参数绑定
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;
}
}
再看看两者的方式
$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哦