php mysqli 还是pdo,php pdo和mysqli对比选择

杭志泽
2023-12-01

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 users

WHERE username = ?

AND email = ?

AND last_login > ?');$query->bind_param('sss', 'test', $mail, time() - 3600);$query->execute();

这样的话,一个个对问号的顺序,也比较麻烦,不大方便。

5 ORM映射的支持

比如有个类user,如下:

classUser

{public $id;public $first_name;public $last_name;public functioninfo()

{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 way

if ($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();

 类似资料: