Выбор API

PHP предоставляет различные API для доступа к MySQL. Ниже показаны API, предоставляемые модулями mysqli и PDO. В каждом примере кода создаётся соединение с сервером MySQL запущенном на сервере "example.com" с использованием логина "user" и пароля "password" и выполняется запрос к нему.

Пример #1 Сравнение MySQL API

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Привет, дорогой пользователь MySQL!' 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 'Привет, дорогой пользователь MySQL!' 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 и 8.x Да Да
Статус разработки Активный Активный
Жизненный цикл Активный Активный
Рекомендовано для новых проектов Да Да
ООП интерфейс Да Да
Процедурный интерфейс Да Нет
API поддерживает асинхронные, неблокирующие запросы mysqlnd Да Нет
Постоянные (persistent) соединения Да Да
API поддерживает кодировки (charset) Да Да
API поддерживает подготовленные запросы на стороне сервера Да Да
API поддерживает подготовленные запросы на стороне клиента Нет Да
API поддерживает хранимые процедуры Да Да
API поддерживает множественные запросы Да Большинство
API поддерживает транзакции Да Да
Можно контролировать транзакции посредством SQL Да Да
Поддерживает всю функциональность MySQL 5.1+ Да Большинство
add a note add a note

User Contributed Notes 4 notes

up
43
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
12
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.
up
-44
Anonymous
7 years ago
These are quite possibly the most paradoxical lines in this table:

API supports non-blocking, asynchronous queries with mysqlnd
     ext/mysqli: Yes     PDO_MySQL: No
API supports client-side Prepared Statements
     ext/mysqli: No     PDO_MySQL: Yes

Apparently it's either asynchronous I/O or the security of bound parameters.
up
-59
michaeln at associations plus dot see eh
11 years ago
Another useful consideration to keep in mind when choosing your library is how extensible it is. Chances are, in any sufficiently advanced development scenario, you're going to be extending your database access class to add a method (or multiple methods) for how to handle database errors and alert the development team of errors and whether to have the code fail immediately or fail gracefully serving the user a user-friendly failure notice.

For example, I have a class where I have added extra parameters to the query() function (and a few others), which accept the __FILE__ and __LINE__ constants to facilitate tracking issues. If this were not reasonably possible with PDO-mysql for example (not sure, never used it), it may make one option or the other much less likely to be viable for your usage case.
To Top