Escolhendo uma API

O PHP oferece diferentes APIs para conexão ao MySQL. Pode-se ver abaixo as APIs fornecidas pelas extensões mysqli e PDO. Cada porção de código cria uma conexão a um servidor MySQL sendo executado em "example.com" usando o usuário "user" e a senha "password". E uma consulta é executada para cumprimentar o usuário.

Exemplo #1 Comparando as APIs do MySQL

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Olá, prezado usuário 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 'Olá, prezado usuário MySQL!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo
htmlentities($row['_message']);

Exemplo #2 Comparando instruções preparadas

<?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']);

Comparação de características

O desempenho geral de ambas as extensões é considerada aproximadamente a mesma, embora o desempenho da extensão contribui somente para uma fração do tempo total de uma requisição web do PHP. Frequentemente, o impacto é tão baixo quanto 0,1%.

  ext/mysqli PDO_MySQL
Versão em que foi introduzida no PHP 5.0 5.1
Incluída no PHP 7.x e 8.x Sim Sim
Estado do desenvolvimento Ativo Ativo
Ciclo de vida Ativo Ativo
Recomendado para novos projetos Sim Sim
Interface POO Sim Sim
Interface Procedural Sim Não
API suporta consultas sem bloqueio assíncronas com mysqlnd Sim Não
Conexões persistentes Sim Sim
API suporta conjuntos de caracteres Sim Sim
API suporta Instruções Preparadas no lado do servidor Sim Sim
API suporta Instruções Preparadas no lado do cliente Não Sim
API suporta Procedimentos Armazenados Sim Sim
API suporta Múltiplas Instruções Sim A maioria
API suporta Transações Sim Sim
Transações podem ser controladas com SQL Sim Sim
Supporta toda a funcionalidade do MySQL 5.1+ Sim A maioria
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