標籤:
1)總的比較
|
PDO |
MySQLi |
資料庫支援 |
12種不同的資料庫支援 |
支援MySQL |
API |
OOP |
OOP + 過程 |
Connection |
Easy |
Easy |
具名引數 |
支援 |
不支援 |
對象映射支援 |
支援 |
支援 |
預先處理語句 (用戶端) |
支援 |
不支援 |
效能 |
快 |
快 |
支援預存程序 |
支援 |
支援
|
2 串連方式
先來看下兩者串連資料庫的方式:
// 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‘);
3 資料庫支援
PDO支援多種資料庫,但MYSQLI只支援MYSQL
4 具名引數name parameter
PDO的方式:
$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‘);
而MYSQLI則麻煩點,不支援這樣,只能:
$query = $mysqli->prepare(‘SELECT * FROM usersWHERE username = ?AND email = ?AND last_login > ?‘);$query->bind_param(‘sss‘, ‘test‘, $mail, time() - 3600);$query->execute();
這樣的話,一個個對問號的順序,也比較麻煩,不大方便。
5 ORM映射的支援
比如有個類user,如下:
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用面向過程的方式:
if ($result = mysqli_query($mysqli, $query)) { while ($user = mysqli_fetch_object($result, ‘User‘)) { echo $user->info()."\n";
}}
MYSQLI採用面向過程的方式:
// MySQLi, object oriented wayif ($result = $mysqli->query($query)) { while ($user = $result->fetch_object(‘User‘)) { echo $user->info()."\n"; }}
6 防止SQL注入方面:
PDO 手工設定
$username = PDO::quote($_GET[‘username‘]);$pdo->query("SELECT * FROM users WHERE username = $username");
使用mysqli
$username = mysqli_real_escape_string($_GET[‘username‘]);$mysqli->query("SELECT * FROM users WHERE username = ‘$username‘");
7 preparestament
PDO方式:
$pdo->prepare(‘SELECT * FROM users WHERE username = :username‘);$pdo->execute(array(‘:username‘ => $_GET[‘username‘]));
MYSQLI:
$query = $mysqli->prepare(‘SELECT * FROM users WHERE username = ?‘);$query->bind_param(‘s‘, $_GET[‘username‘]);$query->execute();
php pdo和mysqli對比選擇