当前位置:Gxlcms > PHP教程 > phppdo与mysqli连接mysql用法对比

phppdo与mysqli连接mysql用法对比

时间:2021-07-01 10:21:17 帮助过:25人阅读

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

人气教程排行