News Archive
PhpRiot Newsletter
Your Email Address:

More information

Uh, uha extending mysqlnd: monitoring and statement redirection

Note: This article was originally published at Planet PHP on 11 October 2011.
Planet PHP

Uh, uha about a year ago Mayflower OpenSource Labs released the mysqlnd user handler plugin (PECL/mysqlnd_uh). The extension lets you extend and replace mysqlnd internal function calls with PHP. Uh, uha mysqlnd internals exported to user space? Who cares as long as it does the trick?! Let me show you seven lines of PHP code to monitor all queries issued by any PHP MySQL application using any PHP MySQL extension (mysql, mysqli, PDO_MySQL) compiled to use the mysqlnd library.


class conn_proxy extends MysqlndUhConnection { public function query($res, $query) { debug_print_backtrace(); return parent::query($res, $query); } } mysqlnd_uh_set_connection_proxy(new conn_proxy());

That's it. Install PECL/mysqlnd_uh and load the above query_monitor.php before your application starts using the PHP configuration directive auto_prepend_file to see all queries issued by your application, including a backtrace. The proof:

cat foo.php query("SELECT 1 AS _one FROM DUAL")-fetchAll(PDO::FETCH_ASSOC)); $mysqli = new mysqli("localhost", "root", "", "test"); $mysqli-query("SELECT 1 AS _two FROM DUAL"); sapi/cli/php -d auto_prepend_file=query_monitor.php foo.php #0 conn_proxy-query(Resource id #5, SELECT 1 AS _one FROM DUAL) #1 PDO-query(SELECT 1 AS _one FROM DUAL) called at [foo.php:3] array(1) { [0]= array(1) { ["_one"]= string(1) "1" } } #0 conn_proxy-query(Resource id #8, SELECT 1 AS _two FROM DUAL) #1 mysqli-query(SELECT 1 AS _two FROM DUAL) called at [foo.php:5]

In preparation for the third and last PHP MySQL webinar, I wrote documentation for PECL/mysqlnd_uh and made the extension compile with PHP 5.4. Get PHP 5.4, get a development version of mysqlnd_uh and give it a try. Both 5.4 and mysqlnd_uh deserve user feedback.

If you happen to use Symfony2, check out by Gordon Franke. Gordon has integrated the monitoring into Symfony2 EventDispatcher.

Any PHP MySQL application | mysql mysqli PDO_MySQL MySQL native driver for PHP (mysqlnd) library Mysqlnd User Handler plugin (PECL/mysqlnd_uh) | MySQL Server

How it works

The mysqlnd user handler plugin provides two PHP classes. The built-in PHP class MysqlndUhConnection is mapped to the mysqlnd C library internal connection class. The built-in PHP class MysqlndUhPreparedStatement gives access to some of mysqlnd's prepared statement class methods.

*.c MySQL native driver for PHP (mysqlnd) library *.c mysqlnd_conn mysqlnd_stmt a *.c Mysqlnd User Handler plugin (PECL/mysqlnd_uh) A provides built-in PHP classes *.php MysqlndUhConnection MysqlndUhPreparedStatement n/a

On the C lev

Truncated by Planet PHP, read more at the original (another 12526 bytes)