mysqli or PDO - what are the pros and cons? [closed]
Well, you could argue with the object oriented aspect, the prepared statements, the fact that it becomes a standard, etc. But I know that most of the time, convincing somebody works better with a killer feature. So there it is:
A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. If you don't want to use an ORM (cause it's a just a quick script) but you do like object mapping, it's REALLY cool :
class Student { public $id; public $first_name; public $last_name public function getFullName() { return $this->first_name.' '.$this->last_name }}try { $dbh = new PDO("mysql:host=$hostname;dbname=school", $username, $password) $stmt = $dbh->query("SELECT * FROM students"); /* MAGIC HAPPENS HERE */ $stmt->setFetchMode(PDO::FETCH_INTO, new Student); foreach($stmt as $student) { echo $student->getFullName().'<br />'; } $dbh = null;}catch(PDOException $e){ echo $e->getMessage();}
Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.
Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.
I've started using PDO because the statement support is better, in my opinion. I'm using an ActiveRecord-esque data-access layer, and it's much easier to implement dynamically generated statements. MySQLi's parameter binding must be done in a single function/method call, so if you don't know until runtime how many parameters you'd like to bind, you're forced to use call_user_func_array()
(I believe that's the right function name) for selects. And forget about simple dynamic result binding.
Most of all, I like PDO because it's a very reasonable level of abstraction. It's easy to use it in completely abstracted systems where you don't want to write SQL, but it also makes it easy to use a more optimized, pure query type of system, or to mix-and-match the two.