php pdo與mysqli串連mysql用法對比

來源:互聯網
上載者:User
  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 parameterpdo方式:

  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、preparestamentpdo方式:

  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();
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.