php pdo和mysqli對比選擇

來源:互聯網
上載者:User

標籤:

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 usersWHERE 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";
  }}

 

MYSQLI採用面向過程的方式:

// MySQLi, object oriented wayif ($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();

 

php pdo和mysqli對比選擇

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.