Are you happy with your logging solution? Would you help us out by taking a 30-second survey? Click here


Very simple and secure PDO wrapper class

Subscribe to updates I use DB

Statistics on DB

Number of watchers on Github 66
Number of open issues 0
Main language PHP
Open pull requests 0+
Closed pull requests 0+
Last commit over 8 years ago
Repo Created over 9 years ago
Repo Last Updated almost 2 years ago
Size 110 KB
Organization / Authornikic
Page Updated
Do you use DB? Leave a review!
View DB activity
View on github
Fresh, new opensource launches 🚀🚀🚀
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating DB for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

Simple database wrapper for PDO

This is a very simplistic database wrapper for PDO, with two goals: Simplicity and Security!

First design goal: Simple!

I did not use the Singleton pattern for this class, because Singletons always involve unnecessarily much code and aren't that nice to use and read. A typical query execution of a Singleton-based DB-class looks like this:

$db = DB::getInstance();
$db->query('SELECT ...');
$db->exec('INSERT INTO ...');

Or, if it's only one query:

DB::getInstance()->query('SELECT ...');

Now, I think this getInstance()-> part of the code neither carries further information, nor is useful in some way. Therefore, I simply left this part out, resulting in:

DB::query('SELECT ...');
DB::exec('SELECT ...');

Much nicer, isn't it?

So, wonder which static methods you can use? All! All methods PDO implements. All calls to static methods are simply redirected to the PDO instance.

Second design goal: Secure!

Apart from this redirecting functionality this class offers two further methods: DB::q() and DB::x(). These methods are shortcuts to DB::query() and DB::exec() with the difference of auto quoting:

    'SELECT * FROM user WHERE group = ?s AND points > ?i',
    'user', 7000 //                   ^^              ^^

See those question marks? These are placeholders, which will be replaced with the arguments passed after the query. There are several types of placeholders:

  • ?s (string) inserts the argument applying string escaping through PDO->quote
  • ?i (integer) inserts the argument applying integer escaping through intval
  • ?a (array) inserts the argument, converting it to a list of string-escaped values: DB::q('SELECT * FROM user WHERE name IN ?a', array('foo', 'bar', 'hello', 'world')); // results in: // SELECT * FROM user WHERE name IN ('foo','bar','hello','world')


There are two versions of this class available, one for PHP 5.3 (DB.php) and one for PHP 5.2 (DB_forPHP52.php). The only difference is, that the former uses __callStatic to redirect the static calls to the PDO instance, the latter simply redefines all methods. (You may obviously use the 5.2 version on PHP 5.3, it actually should be slightly faster.)

So, to get going and use this class, you have to modify the DB::instance method, which by default is defined like this:

public static function instance() {
    if (self::$instance === null) {
        self::$instance = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME,
        self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    return self::$instance;

Replace the arguments of new PDO() to satisfy your needs. Ten, require_once the file and have fun using it!

Short reference

class DB
    // returns the database instance
    public static function instance()

    // DB::query with autoQuote
    public static function q($query, $params, $...)

    // DB::exec with autoQuote
    public static function x($query, $params, $...)

    // autoQuote as described above
    public static function autoQuote($query, array $args)

    // All methods defined by PDO
    // e.d prepare(), quote(), ...
DB questions on Stackoverflow (View All Questions)
  • Lawnchair localStorage (dom storage) conflict with indexed-db adapter
  • Not inserting correct characters in SQLyog DB from C#
  • The model backing the '--Context' context has changed since the database was created - but db is new production database
  • Using Mongo DB uisng Java in AWS
  • Node.js and Oracle DB: Insert query statement doesn't work
  • How to show data from a db on a page in a web app?
  • Graph DB .NET Integration Maturity
  • Laravel query builder returning NULL results when they are clearly in the DB
  • Rails Unconventional DB Structure, is this problematic for associations?
  • Including .db file in JAR (Eclipse)
  • Can I pause DBCP while performing DB maintenance?
  • Choosing grandparent table of db with Django - solved
  • How to connect sql developer to a database on localhost? instance=sqlexpress, db name = Equipment
  • Update cscope db and ctags for just modified files in large projects
  • Can i use Azure DB with DreamSpark for Android Programing?
  • Updating DB with JSON and PHP (Android)
  • How to JUnit test the jpa-code using javadb without modifying the original db?
  • Best practice for uploading delimitated files and insert ing into DB? Having Issues
  • hibernate: Couldn't connect to DB from eclipse
  • Search from two fields in DB Mc access
  • Way to connect to paradox db via internet
  • Get Data from DB every 5 sec and send it through AJAX to Views
  • Get and store value from Firebird db (C#)
  • Searching file contents without storing the file in db
  • How to link Seller and Product table in ecommerce db?
  • Can redis supports queries like sql join and group by while replacing sql DB with Redis?
  • Is there a way of using NHibernate without connection to DB?
  • mongo db insert data in other db (php)
  • How can I render a this design in reactJS and Redux with each item from a NoSQL db like pouchdb
  • Upserting in Mongo DB using official C# driver
DB list of languages used
Other projects in PHP