Select Page

At the moment the database object implemented in WordPress (wpdb) relies on the mysql extension (mysql_connect). As PHP 5.5 will not support the mysql extension anymore and it’s highly recommended to use the mysqli extension with MySQL versions 4.1.3 or later, I was looking for a way to use the mysqli extension with WordPress without too much hacking.

Fortunately WordPress offers a way to include own code before the database object (wpdb) get’s initialized. This is found in wp-includes/load.php in function require_wp_db().

function require_wp_db() {
	global $wpdb;

	require_once( ABSPATH . WPINC . '/wp-db.php' );
	if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
		require_once( WP_CONTENT_DIR . '/db.php' );

	if ( isset( $wpdb ) )
		return;

	$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
}

The function searches for a file named db.php in wp-content and includes it if it exists. If the $wpdb object exists after including db.php, WordPress will not create the default $wpdb object.

So my idea was to extend the original class wpdb (found in wp-includes/wp-dp.php), overwrite all methods which make use of PHP’s mysql_* functions and replace them with the mysqli_* counterparts (as far as possible). Before the class gets defined, the script checks if the server is ready to use mysqli. So far it checks if PHP version is >= 5 and if the function mysqli_connect exists.

I was not sure if it would work, but the first try worked like a charm with my current WordPress project, which has several active plugins. To check if the class is active, I put those lines in my plugin for that project:

global $wpdb;
var_dump($wpdb->dbh);

The result is
object(mysqli)#2 (18) { ["affected_rows"]=> int(1) ["client_info"]=> string(78) "mysqlnd 5.0.8-dev - 20102224 [...]
what shows that $wpdb is working with an mysqli object internally.

With the constants DB_PORT and DB_SOCKET you can configure a custom db port and socket to use for the connection.

But to make this clear: This is just a test and not suitable for productive use right now.

There are some ToDo’s. Functions mysql_num_fields and mysql_free_result have no counterparts for mysqli. The constants MYSQL_NEW_LINK and MYSQL_CLIENT_FLAGS are not supported yet. For the first try I simply used mysqli_connect to test it. In future versions we could try to use mysqli_real_connect instead to support the client flags. And there are definitely some more powerful options to boost the MySQL performance with the mysqli extension. I did not have the time to think about yet.
If you want to try it for yourself, get the file db.php and put in your wp-content directory.

Feel free to improve it and let me know your experiences.

Get it at https://github.com/ifeelweb/mysqli-for-WordPress