首頁 >後端開發 >php教程 >php pdo與mysqli連接mysql用法對比

php pdo與mysqli連接mysql用法對比

WBOY
WBOY原創
2016-07-25 08:51:42855瀏覽
  1. // pdo

  2. $pdo = new pdo("mysql:host=localhost;dbname=database", 'username', 'password');

  3. // mysqli, 面向过程方式

  4. $mysqli = mysqli_connect('localhost','username','password','database');

  5. // mysqli, 面向对象

  6. $mysqli = new mysqli('localhost','username','password','database');

复制代码

3、数据库支持 pdo支持多种数据库,但mysqli只支持mysql

4、命名参数name parameter pdo方式:

  1. $params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);
  2. $pdo->prepare('
  3. select * from users
  4. where username = :username
  5. and email = :email
  6. and last_login > :last_login');
复制代码

而mysqli则麻烦点,不支持这样,只能:

  1. $query = $mysqli->prepare('
  2. select * from users
  3. where username = ?
  4. and email = ?
  5. and last_login > ?');
  6. $query->bind_param('sss', 'test', $mail, time() - 3600);
  7. $query->execute();
复制代码

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

5、orm映射的支持 比如有个类user,例如:

  1. class User
  2. {
  3. public $id;
  4. public $first_name;
  5. public $last_name;
  6. public function info()
  7. {
  8. return '#' . $this->id . ': ' . $this->first_name . ' ' . $this->last_name;
  9. }
  10. }
  11. $query = "SELECT id, first_name, last_name FROM users";
  12. // PDO
  13. $result = $pdo->query($query);
  14. $result->setFetchMode(PDO::FETCH_CLASS, 'User');
  15. while ($user = $result->fetch())
  16. {
  17. echo $user->info() . "n";
  18. }
复制代码

mysqli用面向过程的方式:

  1. if ($result = mysqli_query($mysqli, $query)) {
  2.   while ($user = mysqli_fetch_object($result, 'User')) {
  3.   echo $user->info()."n";
  4.   }
  5. }
复制代码

6、防止sql注入(php防止sql注入的方法解析): pdo 手工设置

  1. $username = pdo::quote($_get['username']);
  2. $pdo->query("select * from users where username = $username");
复制代码

使用mysqli:

  1. $username = mysqli_real_escape_string($_get['username']);
  2. $mysqli->query("select * from users where username = '$username'");
复制代码

7、preparestament pdo方式:

  1. $pdo->prepare('select * from users where username = :username');
  2. $pdo->execute(array(':username' => $_get['username']));
复制代码

mysqli方式:

  1. $query = $mysqli->prepare('select * from users where username = ?');
  2. $query->bind_param('s', $_get['username']);
  3. $query->execute();
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn