Simple yet efficient PDO wrapper
Making your code shorter.
The main problem with both PDO and mysqli prepared statements is that the mechanism was designed for the multiple execution, when prepare and bind are called only once, and then execute is called multiple times with different data sets. That's why the code is so verbose.
However, in reality, multiple execution is seldom used, while most of time prepared statements are used to execute the query only once. As a result, for the every single query we are bound to write the same repetitive routine again and again:
$stmt = $pdo->prepare("SELECT * FROM users WHERE sex=?");
$stmt->execute([$sex]);
$data = $stmt->fetchAll();
It would have been better if execute() returned PDOStatement, allowing neat method chaining:
$data = $pdo->prepare($sql)->execute($params)->fetch();
But alas, execute() is returning a boolean.
Either way, even such an approach would be superfluous most of time, as we don't need separate prepare and execute calls.
To solve this inconvenience, it would be a good idea to have a function similar to Postgres' pg_query_params() (or mysqli's execute_query) to encapsulate the prepare/execute routine and return the statement.
A simple PDO function
The simplest solution would be to create a function that accepts a PDO object, an SQL query and an optional array with parameters for execute() and returns a PDOStatement object:
function pdo($pdo, $sql, $args = NULL)
{
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
It would serve if your code is mostly procedural. Given you can chain any PDOStatement method directly to this function's call, most of queries will become just one-liners:
// getting the number of rows in the table
$count = pdo($pdo, "SELECT count(*) FROM users")->fetchColumn();
// the user data based on email
$user = pdo($pdo, "SELECT * FROM users WHERE email=?", [$email])->fetch();
// getting many rows from the table
$data = pdo($pdo, "SELECT * FROM users WHERE salary > ?", [$salary])->fetchAll();
// getting the number of affected rows from DELETE/UPDATE/INSERT
$deleted = pdo($pdo, "DELETE FROM users WHERE id=?", [$id])->rowCount();
// insert
pdo($pdo, "INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);
// named placeholders are also welcome though I find them a bit too verbose
pdo($pdo, "UPDATE users SET name=:name WHERE id=:id", ['id'=>$id, 'name'=>$name]);
// using a sophisticated fetch mode, indexing the returned array by id
$indexed = pdo($pdo, "SELECT id, name FROM users")->fetchAll(PDO::FETCH_KEY_PAIR);
A simple Database class
The next step would be, however, to create a class that would contain the necessary PDO connection code, as well as useful run() function. Note that for simplicity this class made to work with mysql database only.
class DB
{
public $pdo;
public function __construct($db, $username = NULL, $password = NULL, $host = '127.0.0.1', $port = 3306, $options = [])
{
$default_options = [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$options = array_replace($default_options, $options);
$dsn = "mysql:host=$host;dbname=$db;port=$port;charset=utf8mb4";
$this->pdo = new \PDO($dsn, $username, $password, $options);
}
public function run($sql, $args = NULL)
{
$stmt = $this->pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
Now this class can be included as a constructor parameter in all other classes that require a database interaction. Notice that PDO variable is made public. That's because we will need to access the full PDO functionality through this variable.
To use this class first create an instance, like this
$db = new DB($dbname, $user, $password);
and then used just like the function but instead of rather clumsy pdo($pdo, $sql); we can writh it as $db->run($sql);
$db->run("INSERT INTO users VALUES (null, ?,?,?)", [$name, $email, $password]);
$id = $db->pdo->lastInsertId();
Note that in case we need a native PDO method or property, it can be accessed through $pdo property.
Extending PDO
Another way to access the full PDO functionality would be to extend our object from PDO.
Let's extend PDO and add a new method called run() (as I prefer short names for the frequently called functions). Also, for convenience, we can add the most essential connection options to the constructor:
class MyPDO extends PDO
{
public function __construct($dsn, $username = NULL, $password = NULL, $options = [])
{
$default_options = [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$options = array_replace($default_options, $options);
parent::__construct($dsn, $username, $password, $options);
}
public function run($sql, $args = NULL)
{
$stmt = $this->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
and now we've got a new class MyPDO which works as old PDO in either way save for the addition of one new method that let us run a prepared query in a single call:
$data = $pdo->run("SELECT * FROM users WHERE sex=?",[$sex])->fetchAll();
Also we just included most useful configuration options by default, but they can be overwritten at runtime.
Using PDO in other classes
Another problem is the availability of PDO instance. Just like any other variable, it is bound to its scope and by default unavailable in any function or class' method. There are may approaches to solve this problem but only one should be really used:
The true OOP way
For simplicity, Dependency injection stands for just passing all the required services through class constructor.
So if your code is object-oriented, then you may stick to the above MyPDO class solution, passing its instance around using other classes' constructors:
class User
{
protected MyPDO $db;
protected $data;
public function __construct(MyPDO $db)
{
$this->db = $db;
}
public function find($id)
{
$this->data = $this->db->run("SELECT * FROM users WHERE id = ?", [$id])->fetch();
}
}
And then use it this way:
$mypdo = new MyPDO('mysql:host=localhost;dbname=test;charset=utf8');
$user = new User($mypdo);
$user->find($id);
Creating classes dynamically
The above approach will do as long as all your classes are instantiated manually. However, oftimes a PHP application implements a router, which creates required classes on the fly, based on the routing rules. In this case you will need a Dependency Injection Container, that will store single instance of the database connection class, and provide it as a parameter (inject it) in all classes it creates, in case they have Database class in their constructir.
Related articles:
- (The only proper) PDO tutorial
- PDO Fetch Modes
- Fetching objects with PDO
- An SQL injection against which prepared statements won't help
- A fair comparison of mysqli vs. PDO
- Authenticating a user using PDO and password_verify()
- Your first database wrapper's childhood diseases
- MCVE or How to debug database interactions with PDO
- A cargo cult prepared statement
- Whitelisting helper function
Comments:
Hi! I created a GitHub project based on your wrapper (extending the PDO method). The only changes I made were to align it with PSR standards: https://github.com/a-le/PDOwrapper
I've also just released MicroDbal, and I wanted to say that your series of articles was incredibly helpful and inspiring during its development: https://github.com/a-le/microDbal
Hope it's okay to share these links here!
This is really nice. I also extended PDO and PDOStatement classes, because default naming is very unlogical. For example to get only one variable, you have to use fetchColumn, I added getVar which calls fetchColumn(). I also added getRow which is fetch(), getCol which is fetchAll(PDO::FETCH_COLUMN).
how do you manage closing pdo connection? And using only one connections at a time if you use different models.
Reply:
Hello Globaliser!
Very good additions! I like the naming, its concise and logical.
Usually I don't bother closing the connection, because it will die with request anyway.
As of using in different models, it is shown right in the article: a single database connection is passed to all models as a constructor parameter.
Could you please explain why the "class MyPDO extends PDO" violates Liskov? There are only two methods: run() and the constructor. The run() method doesn't exist in the PDO class so that can't violate Liskov, and then it's only the constructor left, but Liskov doesn't apply to constructors. So there seems to be no violation of Liskov here?
Reply:
You are right. I added this note because someone scolded me for this code on Stack Overflow and I took their criticism for granted. But since then I learned that it doesn't violate indeed. Removed that note right away.
Just started with PDO a few months ago, and today I came to think about the implementation of a wrapper, like the one you suggested under the section 'A simple PDO class', hence I dropped on this article. First, thanks for sharing! If I may suggest, however. Whenever you return a $stmt object from a function within your wrapper class, you could instead add an additional PDOStatement $stmt property to your implemented class, which you would then populate with the obtained statement instance. In this way, you could also integrate functions of the PDOStatement class within your wrapper class, by calling it via $this->stmt->yourMethod(); or similar. Is a detail, but removes some additional verbosity related to calls of methods of the PDOStatement class. If you watch out to only instantiate the class once (e.g. via singleton or whatever approach), this would then also ensure that you've only one statement active at a time, which prevents additional unwanted issues like out of synch errors (https://dev.mysql.com/doc/refman/8.0/en/commands-out-of-sync.html), etc. that could occur with the careless use of statements, etc.
Reply:
Hello!
Thank you for the suggestion, but I genuinely don't understand it. Yes, you could integrate some functions in the class, but you definitely don't need any stmt properties for this. Like, fetchCell($sql, $params) method will just call the run() method inside and return the result right away.
I really don't see any use for the $stmt property. While it will introduce a state to the class, which you should avoid. Please read the https://phpdelusions.net/pdo/common_mistakes#statefulness
And your singleton, apart from being a bad practice in its own right, won't solve this problem at all.
And again. Apart from being harmful, I just can't see how $stmt property can be any useful. Got an example?
Just wondering why in the wrapper do you return
$stmtinstead of the result of theexecute->($args).Reply:
Hello Carlos!
That's a very good question!
First, about true/false. There is no point in returning a boolean because execute will never return false, and always returning true just makes no sense. Why it will never return false? Simply because it would return false only in case of error. But in case of error, an Exception will be thrown, and execute won't return anything.
Now, why it returns $stmt. Simply because it contains the actual query result. Without it you simply won't get any use of the query - neither number of affected rows from UPDATE nor the rows returned by the query.
So right now in October, 2021 - for a brand new web project, not using a major ORM (no Eloquent/Doctrine) - should we be using PDO or your Safe MySQL class? Is your Safe MySQL class only for projects still using mysqli (easy to migrate)?
Reply:
Hello Derek!
I would suggest PDO, or - better - some wrapper for it, such as https://github.com/paragonie/easydb
Hi Great article, however in your first DB class sample there is an error in the construct function. You have a variable called $post = 3306 that should be $port = 3306. It still works but throws up a missing variable error. Thanks for sharing your knowledge.
Wonderful articles, well explained and comprehensive. Kudos and thx.
A small typo in "A simple PDO class" section - ou define a parameter $post (typo) but for constructing dsn you use $port,,, additionlly might as well use $charset too !!
Please recommend 3, 5 or 10 php books that will skyrocket my programming skills (php especially) and make me a guru. I am learning mvc and codeigniter now. My background is in computer science.
I agree with Daniel, I don't see how extending the base PDO class by only adding functionality would be a violation of LSP. Since none of the parent functionality was changed, you would be able to pass around the MyPDO in lieu of a normal PDO object to every class that expects a PDO and you wouldn't have any breaking behavior.
Hi, can class MyPDO also be used within PHP 8 ?
Hi, thanks for the excellent tutorial and your whole site which is a true treasure trove for PHP programming.
I have two questions:
in The static solution for the Object Oriented Code
What is the difference between this-> vs this->pdo->
Thank you for the article. I found it very helpful in addressing a single database. How might I use this code to address multiple databases? Seems like I would have to have a different class for each database name with this architecture. Is that correct? It doesn't seem like that is the right way to do it; what am I missing?
Reply:
Hello Gillie!
This is an issue that concerned me for a long time already. I have several approaches in mind and will be happy to provide some. Please pick a particular wrapper from those present in this article and I will add a dedicated section featuring this wrapper supporting different databases.
What about making this PDO connexion persistant? (PDO::ATTR_PERSISTENT => true)
How well will the code perform in a multithreaded and multiuser environment ? By an example won't the PDO be filled by a "prepare" instruction run at the worst moment ?
Super useful PDO Singleton Class. Thanks!
Thanks for your articles. I've enjoyed reading them, and I've learned a lot. I have what is probably a basic PHP question. I have unsuccessfully googled to find an answer. In class User
how is the variable $db populated by this :
Thank you.
Reply:
Hello Neil!
Sorry, I don't really understand your question. There is an example above
And then this $mypdo variable is assigned to the class variable $db and can be used in the class, as it showin in the example function find:
Here the MyPDO instance is accessed via $this->db.
Hope it is clear now, but feel free to ask if not
Do we need to restate the options in the MyPDO class if it was already specified in the database connection file? I checked over both your connection code and this class code, and the options are exactly the same.
Reply:
Hello Mandyrobin!
Of course not!
the defaults in the MyPDO class are set only for the convenience. So, once you have them set, you don't have to repeat them in the options.
any recomendations for postgres in a singleton?
Amazing! It was right there in front of me all this time! For some reason, I was stuck using fetch() and getting every exception in the book when I tried to work around it :( Thank you & cheers!
With the static solution, how could I set the fetch mode to have it return a class instead of an object for specific queries?
Reply:
Hello Guillermo!
Thank you for a good question. Actually, the approach would be the same:
When fetching a single record, you can use fetcjObject() method. And when using fetchAll() you can provide a class name as a parameter. Read more in this article, https://phpdelusions.net/pdo/objects#fetch
Hi! Thanks for this tutorial! I have a question to "The static solution for the Object Oriented Code": could it be a problem, when i do not seperate $instance and $pdo - and return self::$pdo in instance() itself? I ask, because, if i do so, then there is no need for a proxy. Here the code:
(So sorry for the very ugly way my previous comment formatted)
Reply:
No problem, I formatted it :)
How do I encode a complex query that has optional parts, determined by variable values? Here's my old code:
This example is simpler than some of the more complicated ones, which may have a number of clauses. I could do a very complex nested if to tease out all possibilities into separate DB::run calls, but that would make for very ugly code.
Reply:
Hello Kevin!
The principle is pretty much the same. Here is an example I wrote, which, I hope, perfectly fits your case: https://phpdelusions.net/pdo_examples/dynamical_where
Please check back if you still have some questions!
I'm a bit puzzled about the true OOP way. Does it eliminate the problem of multiple instances. If every time in a php script a new object is made that needs a connection to the database would I create a new PDO object as well. Is it really recommended to make a new connection for every single connection case like this?
Reply:
Hello Juleyn!
Of course not! You are supposed to create a connection only once and then pass it around into other objects that need it, through a constructor, like
And so on.
So basically it goes this way. Does it make sense now?
Hi,
Thanks for this tutorial. One noob question: in the "The static solution for the Object Oriented Code" section, the User class, we are meant to add a return to the find() method in order to get anything into $user->find($id), right?
Reply:
Hello Andy!
Thank you for a good question.
It depends on what a User class is. If it represents a User entity, we don't have to return anything, populating the data inside, as shown in the example.
But I have to agree that naming is not that precise, and a method find() should rather belong to a class UserMapper, which finds a user and then creates and returns an instance of a User class. In this case it should indeed have a return statement.
Apologies, it isn't from the lack of info in the fetchAll. It is from a lack of Args so if your SQL is all in the " " without anything to prepare it fails.
Reply:
Thanks again. So I hope it is fixed now.
So in a follow up to the comment from Someone on 13.05.17 04:45 there is an error when running the fetchall() with no args in PHP7. The info in this comment fixes the error if you don't use any arguments in the fetchall(). But in my case I want to use it both ways so with that change it works without but then if we try your example ->fetchAll(PDO::FETCH_KEY_PAIR) it fails with an error Uncaught Error: Call to a member function query(). How do we get it to work with both?
Reply:
Hello Justin!
Thank you for reminding of this one. It was a stupid copy paste and now I finally fixed it.
Hey!
Beginner here.
I have a few concerns:
1) With the require-file method, how does the script always know that we're already on a connection and not to reset it?
2) Can you pelase explain a bit why did you initiate construct and clone in this context? I don't see the point.
3) What is __callStatic used for at this point? I really don't understand.
Having read on dependency injection, overloading and such, I still can't wrap my head around it, personally, if you could add some comments to the code, that'd be swell!
I know it's out of the scope, but people who are interested in learning the inner workings and not just copy could really appreciate it! :)
Cheers.
Reply:
Hello Tantrum!
Thank you for excellent questions, which are right in to the spot.
require 'mypdo.php';will reset the connection, whereasrequire_oncecalls will be just ignored.For the second method it's much simpler - it should be called with
require_once, and will be always available without reset.these empty methods are rather cargo cult code that i just mindlessly copy-pasted from some singleton implementation. From what I understand now, they are to prevent rewriting them after extending this class and therefore should be private, not protected.
__callStaticis a neat trick that is working as a proxy to PDO instance, translating each call to mypdo into PDO method, ieDB::preparebecomesPDO::prepare()and so on.I will try to add more info to the article, and although dependency injection is indeed a bit out of scope, but I';ll try to cover it too.
You are welcome to ask more questions!
On PHP7 I got an error. This fixed it for me:
Find line 42: return $this->query($sql);
Replaced on line 42: return self::$instance->query($sql);
Reply:
Thank you, fixed!
Looks nice. How does this class hold up against SQL injection? ...are there any gotchas?
How can I use the same placeholder in PDO wrapper? For example I have this SQL command:
After running this I get "PDOException: SQLSTATE[HY093]: Invalid parameter number"
Reply:
Hello Dmitry!
Thank you for the good question. Named parameters can be reused only if emulation is turned on.
So, you can either remove PDO::ATTR_EMULATE_PREPARES from connection parameters, or add this line
to switch it on.
Feel free to ask other questions!
Thanks for the good explainations! I noticed your class has a catch, beacause being a Singleton it should not be possible to create another instance of the class: var_dump( DB::instance()); $db = new DB; var_dump( $db); Notice ID #2
The soluion, makes these private: private function construct() {} private function clone() {}
HTH Best regards Cor van Dooren
Reply:
Hello Cor!
Indeed I made it wrong. Fixed now. Thank you for a catch!
I have some question in database.php
What advantage using define instead of const ? const DB_HOST = 'localhost', DB_NAME = 'test', DB_USER = 'root', DB_PASS = '', DB_CHAR = 'utf8'; // more readable.
Looks like some function have not been used or empty. There are three of them construct(), clone(), and __callStatic. Why not just delete them ?
Maybe i was wrong. Thanks.
Reply:
Hello Goe!
There is no advantage in the constants definition, just a matter of taste.
While for the empty functions, I have to admit it's like a cargo cult programming on my side. I just found somewhere a singleton example and adapted it for my needs. I should have checked it before use. Will revise the code soon
you have a wuery near the top of this page that should be query. "while most of time prepared statements are used to execute the wuery only once"
Reply:
Thank you, fixed!
Thanks Got It, I was not sure actually. Anyway, nice article about PDO easy to understand.
Thanks for the suggestion. "Just set encoding in the DSN" How would I do this?
Reply:
Just as it shown in the example above, note the "charset" keyword inthe DSN connection string.
Nice Wrapper why you are not using PDO::ATTR_EMULATE_PREPARES => FALSE, It is more safer, isnt it??
Reply:
Nope, both options are equally safe. Just set encoding in the DSN, and there will be not a problem with security.