The mysql
extension is officially deprecated. This means that there are no guarantees of its further support (including from the point of view of security). Therefore, this extension can not be used in any new project.
There remains the choice between mysqli
and PDO
.
mysqli
extension
mysqli
is the easiest replacement for mysql
. Most of the functions and methods of mysqli
have a syntax similar to the syntax of the mysql
extension. This allows you to simply switch from one extension to another. For example:
// mysql $link = mysql_connect(); $res = mysql_query('SELECT * FROM tbl', $link); var_dump(mysql_fetch_assoc($res)); // mysqli $link = mysqli_connect(); $res = mysqli_query($link, 'SELECT * FROM tbl'); var_dump(mysqli_fetch_assoc($res));
At the same time, there are a number of improvements related to security (placeholders) and the object approach. The obvious minus mysqli
- binding code to work with MySQL. In some cases, this may make it difficult to switch to using other databases (if this is of course necessary).
PDO
extension
PDO
is an additional level of abstraction above the database. Theoretically, the same PHP code can work with any SQL compatible database, if there is a corresponding PDO driver for it. (In practice, the problem with different databases still remains due to differences in SQL syntax.) PDO
preaches an object approach, therefore, the code will differ significantly from code using mysql
. For example:
// mysql $link = mysql_connect('localhost', 'user', 'pass'); mysql_select_db('testdb', $link); $res = mysql_query('SELECT * FROM tbl', $link); var_dump(mysql_fetch_assoc($res)); // PDO $dbh = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass'); $stm = $dbh->prepare('SELECT * FROM tbl'); $stm->execute(); var_dump($stm->fetch(PDO::FETCH_ASSOC));
Among other things, PDO
provides a set of additional features related to security (placeholders) and the speed of the query (prepared requests). Although these features are not mysql
, some of them are implemented in mysqli
.
I summarize : in most cases, I would recommend using PDO
, since the interface for working with mysqli
too low-level and often requires creating your own level of abstraction over the database.