Introduction
Long gone are the days of using the mysql_
extension, as its methods have been deprecated since PHP 5.5 and removed as of PHP 7. Alas, the internet is still plagued with a ton of old tutorials that beginners will simply copy/paste and use on a shared hosting platform with an older PHP version, thus continuing its legacy.
If you are using MySQL or MariaDB in PHP, then you have the ability to choose either MySQLi or PDO. The former is simply an improved version with procedural and OOP support and added prepared statements, while the latter is an abstraction layer that allows you to use a unified API for all 12 database drivers it supports. Though it should be mentioned that MySQL is undoubtedly the most popular database to use in the PHP world anyway.
- Extension=pdo.so extension=pdomysql.so Creating a MySQL Database. Let's start by creating a MySQL using the mysql client. In your terminal, run the following command: $ mysql -u root -p Enter your MySQL database password when prompted. Next, run the following SQL instruction to create a database.
- Installation or Setup. PDO is a universal database connection command in PHP, it support 12 different database type e.g MySQL, MongoDB, NoSQL.A big bonus about PDO is that it calculate your code to support the database type, so you don't need to make any.
In theory, one might assume the discussion should be over. We don't need a vendor-specific API for every type of database that exists, as it's so much simpler to use just one. While there's certainly a lot of truth to this, the problem is that PDO_MYSQL
simply doesn't have all of the newest and most advanced features MySQLi does. I honestly don't understand why this is the case, as it would completely eliminate any reason to use the vendor-specific API. That said, I'd imagine that most people don't need these extra features, but there are definitely some who do.
See full list on digitalocean.com. Installation or Setup. PDO is a universal database connection command in PHP, it support 12 different database type e.g MySQL, MongoDB, NoSQL.A big bonus about PDO is that it calculate your code to support the database type, so you don't need to make any chance when moving over to another database system.
For anyone who's interested, here's a full writeup of PDO and MySQLi.
PDO Advantages
MySQLi has quite a few aspects to play catchup with PDO. It needs to adds features like:
- Allow to pass variables and values directly into execute
- Ability to auto-detect variable types (What actually happens is that everything is treated as a string when sent to the sever, but is converted to the correct type. This works 100% of the time with native prepared statements but doesn't work with certain edge cases, such as LIKE with emulation mode.)
- Provides an option to have automatically buffered results with prepared statements
- Named parameters (though useless with emulation mode turned off in PDO, as you can only use the same name once)
As you can see, there are quite a few things MySQLi should learn from PDO if it wants to stay relevant.
If it does, then there should really be no difference at all. People always talk about how you'd have to learn a whole new extension, yet they're actually already nearly identical for the most part. For this article, I'll be using native prepared statements, but emulated ones are perfectly acceptable as well. Here's a short writeup on the differences between the two.
MySQLi Advantages
PDO is also missing some features, albeit far less important ones for most users, such as:
- Ability to get more info on affected rows, like updating a row with the same values (can be done in PDO as a constructor setting you can't change it later)
- Proper database closing method
- Multiple queries at once (though it can if emulation mode is turned on in PDO)
- Automatic cleanup with persistent connections
So Which Should I Use?
My opinion is that PDO should be used by default, especially beginners, due to its versatility, general predictability and useful fetch modes. However, MySQLi would be a better choice for advanced users who want the newest, MySQL-specific functionality.
It's somewhat ironic that more experienced PHP developers tend think PDO is the only acceptable option 100% of the time, while beginners tend to use MySQLi. This is absolutely nutty from both ends. Of course most developers don't really need the extra advanced features MySQLi offers, but it certainly could be extremely useful for some, as previously mentioned.
It's especially curious that novices are scared to try something 'new' and switch to PDO, while a lot of advanced users recite the good ole 'ease of switching from database driver' argument as PDO's advantage. Anyone who believes the myth that you can easily switch among databases in PDO seamlessly has obviously never attempted to do so. Each driver is different, and a switch from Microsoft SQL Server to MySQL will certainly not be automated. First of all let's make one thing clear, the syntax is very similar — almost identical, and I will present that in examples. PDO is also not some abstraction layer over MySQLi, but rather over PDO_MYSQL.
If PDO does end up keeping up with all of the latest or distinct MySQL functionality, then I could see why MySQLi should go away; I'd even encourage it, if it ends up being the case. Though PDO does have several driver-specific features, it doesn't have all nor keep up with the latest. This is precisely why I don't think MySQLi and PDO aren't necessarily competitors, but rather two powerful libraries with completely different focuses for now. Obviously PDO should be more widely used, however. But as said before, the difference is pretty much negligible as is anyway. As mentioned several times earlier, MySQLi's survival relies on it catching up to PDO, along with PDO primarily sticking with features that are used among most of the DB drivers it supports.
Code Differences
As stated earlier, both PDO and MySQLi are extremely similar, but there's slight differences in syntax. MySQLi follows the old-school PHP snake_case convention, while PDO uses camelCase. Additionally, MySQLi's methods are used as object properties, while PDO uses the traditional syntax for functions.
I'll never understand why both PDO and MySQLi complicated things by forcing you to use two separate methods to use prepared statement. Luckily PDO removed the need to use a dedicated bind function — though I'm not sure why the same isn't done for execute()
. Non-prepared MySQLi and PDO really aren't so bad, and it's only really the unfortunate implementation of prepared statements that caused them to seem verbose. For instance, in the vendor-specific PostgreSQL API you can do it like this. Here's an example of how you'd do a 'non-prepared' query to fetch an associative array with MySQLi and PDO, for reference.
In reality, the best route is to use a wrapper, query builder or ORM. I have a fairly rudimentary MySQLi wrapper you might like. While PDO is a step in the right direction, as you can bind values directly into execute, it's still not ideal. In the class I made, you can chain all of your calls, while passing in the values to bind as a parameter argument. Check out what you can do.
You now have an entire associative array stored in the variable in a far more concise manner. It's strange why both PDO and MySQLi don't do it like this.
For the rest of the tutorial, we'll be using prepared statements, as there isn't a good reason not to use them for SQL injection protection, unless you're using a feature like async, which currently doesn't support them. Otherwise, you'll need to properly manually format your queries.
Creating a New Database Connection
PDO
MySQLi
Insert, Update, Delete
PDO
MySQLi
It should be noted that with PDO, you can chain prepare()
and execute()
, though you won't be to get the affected rows, so I can't see that being useful.
Get Number of Affected Rows
PDO
MySQLi
Get Latest Primary Key Inserted
Notice, how both of these use the connection variable, instead of $stmt
.
PDO
MySQLi
Get Rows Matched
PDO
In PDO, the only way to achieve this is by setting it as a connection option to change the behavior of rowCount()
, unfortunately. This means rowCount()
will either return rows matched or rows changed for your entire database connection, but not both.
MySQLi
This will output an entire string of information, like so:
I have no idea why they thought this would be a wise implementation, as it would be far more convenient in an array. Luckily, you can do this.
Now you can access the values pretty easily. Note, that the value is a string, so you either cast all the values to ints, so can work or strictly check with .
Fetching
Fetch Associative Array
PDO
MySQLi
Fetch Single Row
PDO
MySQLi
Fetch Single Value (Scalar)
PDO
MySQLi
Fetch Array of Objects
PDO
MySQLi
PDO really shines here as you can see. It's very odd why MySQLi doesn't have something like $mysqli_result->fetch_all(MYSQLI_OBJ)
. PDO even takes it a step further and has an awesome way to deal with the annoying default behavior of it getting called after the class constructor, via bitwising it with fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'myClass')
. It's possible to replicate this behavior in MySQLi, but it relies on either leaving out the constructor and relying on the magic __set()
or by only setting it in the constructor if it doesn't equal the default value.
Like
PDO
MySQLi
Fetch Modes
This is by far my favorite feature about PDO. The fetch modes in PDO are extremely useful and it's quite shocking that MySQLi hasn't added them yet.
Fetch Key/Value Pair
PDO
MySQLi
Output:
Fetch Group Column
PDO
MySQLi
Output:
Fetch Key/Value Pair Array
PDO
MySQLi
Output:
Fetch Group
PDO
MySQLi
Output:
Where In Array
PDO
MySQLi
Pdo_mysql Windows
Where In Array With Other Placeholders
PDO
MySQLi
Transactions
PDO
You might be wondering why I'm solely checking for truthiness on execute()
with PDO. This is due to the fact that it can return false, while silently failing. Here's a more detailed explanation.
MySQLi
PDO really shines here as you can see. It's very odd why MySQLi doesn't have something like $mysqli_result->fetch_all(MYSQLI_OBJ)
. PDO even takes it a step further and has an awesome way to deal with the annoying default behavior of it getting called after the class constructor, via bitwising it with fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'myClass')
. It's possible to replicate this behavior in MySQLi, but it relies on either leaving out the constructor and relying on the magic __set()
or by only setting it in the constructor if it doesn't equal the default value.
Like
PDO
MySQLi
Fetch Modes
This is by far my favorite feature about PDO. The fetch modes in PDO are extremely useful and it's quite shocking that MySQLi hasn't added them yet.
Fetch Key/Value Pair
PDO
MySQLi
Output:
Fetch Group Column
PDO
MySQLi
Output:
Fetch Key/Value Pair Array
PDO
MySQLi
Output:
Fetch Group
PDO
MySQLi
Output:
Where In Array
PDO
MySQLi
Pdo_mysql Windows
Where In Array With Other Placeholders
PDO
MySQLi
Transactions
PDO
You might be wondering why I'm solely checking for truthiness on execute()
with PDO. This is due to the fact that it can return false, while silently failing. Here's a more detailed explanation.
Pdo_mysql Install
MySQLi
MySQLi also has a gotcha, but the solution is to convert errors to exception with a global handler. Read about it more here.
Pdo_mysql Driver
Named Paramters
Pdo_mysql.so
This is a PDO-only feature, but it's only useful if emulation mode is turned off. Otherwise, you can only use the same variable once. It should also be noted that the leading colon is not required, but this isn't documented anywhere. It likely will eventually anyway, but you never know, I suppose. You also can't mix ?
placeholders with named ones; it's either one or the other.