PHP 8.3.4 Released!

どの API を使うか

PHP には、様々な MySQL へ接続する API があります。 以下に、mysqli と PDO が提供する API を示します。 それぞれのコードは、"example.com" 上で稼働する MySQL サーバーに ユーザー名 "user"、パスワード "password" で接続するものです。 そして、クエリを実行してユーザーにあいさつします。

例1 MySQL 用 API の比較

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo
htmlentities($row['_message']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo
htmlentities($row['_message']);

例2 プリペアドステートメントの比較

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$statement = $mysqli->prepare("SELECT District FROM City WHERE Name=?");
$statement->execute(["Amersfoort"]);
$result = $statement->get_result();
$row = $result->fetch_assoc();
echo
htmlentities($row['District']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->prepare("SELECT District FROM City WHERE Name=?");
$statement->execute(["Amersfoort"]);
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo
htmlentities($row['District']);

機能の比較

全体的なパフォーマンスは、どれもほぼ同じです。 拡張モジュール自体のパフォーマンスが PHP のウェブリクエストの実行時間に及ぼす影響はごくわずかで、 たいていは 0.1% 程度に過ぎません。

  ext/mysqli PDO_MySQL
どのバージョンの PHP から使えるか 5.0 5.1
PHP 7.x と PHP 8.x に同梱されているか Yes Yes
開発状況 進行中 進行中
ライフサイクル 活動中 活動中
新規開発でおすすめできるか Yes Yes
オブジェクト指向のインターフェイス Yes Yes
手続き型のインターフェイス Yes No
mysqlnd によるノンブロッキングな非同期クエリ Yes No
持続的接続 Yes Yes
文字セット Yes Yes
サーバーサイドのプリペアドステートメント Yes Yes
クライアントサイドのプリペアドステートメント No Yes
ストアドプロシージャ Yes Yes
複数ステートメント Yes Most
トランザクション Yes Yes
SQL によるトランザクション制御 Yes Yes
MySQL 5.1+ の全機能への対応 Yes Most
add a note

User Contributed Notes 2 notes

up
35
alvaro at demogracia dot com
11 years ago
Apart from the feature list, I suggest you try out both MySQLi and PDO and find out what API design you like most. MySQLi is more powerful and probably more complex to learn. PDO is more elegant and has the advantage that you only need to learn one PHP API if you need to work with different DBMS in the future.
up
6
rellect at gmail dot com
5 years ago
Another point to consider and one of the advantages of PDO is that it's not limited to mysql and supports other database engines such as PostgreSQL, SQLite, etc.
To Top