Using wpdb in core PHP non WordPress Projects

If you are a WordPress developer you would definitely be aware of the $wpdb variable. $wpdb makes it easy to query any table in your database and handle the result data as an array with column names as keys or as an object with properties as column names. $wpdb also provides the prepared statement for escaping mysql injection.

$wpdb is nothing but the object of the wpdb class which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database. The class source code is loosely based on the ezSQL class.

When moving from a WordPress to non WordPress projects, using the mysql/mysqli functions directly can be little daunting.
So below is the modified wp-db class that you can require_once in your php files and use the normal wpdb functions in your core PHP projects as you would in a usual WordPress Projects.
Make sure you set some global config variables at the beginning of the file before starting. Click on the links below to download the file and view source code.

Download SourceView Source

And here’s how to use this class

First require the class source file in your project and call the global $wpdb variable which is the object of this class.

That’s it. Now you can use all the WordPress wpdb functions like get_results, get_rows and so on…

For those of you who haven’t used WordPress or wpdb, below is the quick view of simple select queries using wpdb.

Select Query

Fetching multiple result rows

So, for a simple SELECT query with muliple rows the code goes as below

By setting the second parameter to ARRAY_N and ARRAY_A the result set will be fetched as numeric and associative array respectively.
See example below

Fetching single result row

There are many more things apart from SELECT that this class provides. For more functions and details on using them you visit the wpdb class reference page on the official wordpress codex. All the functions listed there can be used with this class.

Join the discussion

  1. Thank you, it works like a charm.

  2. Netto says:

    Thanks bro, this solve my problem

Leave a Reply

Your email address will not be published. Required fields are marked *