06 Aug

WordPress Database Interaction with $wpdb.


There are a number of ways to interact with the database when developing for WordPress. Wherever possible, you should use the many core WP functions for working with database data, for example: get_pages can return an array of pages that meet criteria you specify.

However sometimes you may need to deal with the db a little more directly to craft queries that go beyond the scope of the standard core WP functions. Unfortunately we still see WP plugin or theme developers doing this in ways that are vulnerable to SQL injections, and it only takes one security hole to put your entire site at risk.

PHP MySQL Options

The old mysql_* functions should never be used – not only is there no prepared statement support meaning you are relied upon to carry out all sanitizations (or risk SQL injection), but these functions are deprecated in newer versions of PHP.

PHP’s newer mysqli_* functions are a vast improvement, with support for prepared statements, multiple statements, transactions, debugging capabilities, and it’s OO (object orientated).

There’s also PDO (PHP Data Objects) – a database abstraction layer, which provides a consistent interface which can be used with a variety of DB drivers (MySQL, MS SQL, Firebird, PostgreSQL and others). This means your PHP application can be run on a wider variety of server configurations in a consistent manner.

Using any of the above options for database interactions in WordPress would see alot of work from the WordPress core developers gone to waste. Here is a little reference guide to get you on the right track to deal with db calls the recommended, safest way – using $wpdb.
Read article