-
-
// 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,例如:
-
- 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";
- }
- }
复制代码
6、防止sql注入(php防止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();
复制代码
|