Search code examples
phpmysqlclassextend

Extend MySQLi Class to EXPLAIN SQL queries on page


how can I extend the MySQLi class to explain all SQL queries on a given page?

Thanks.


Solution

  • There are several ways to do this. Here is one:

    To start, you can get an explanation by simply prepending "EXPLAIN " to the mysql statement. See http://dev.mysql.com/doc/refman/5.0/en/explain.html for details on Mysql's explain.

    Knowing that Mysql invocation, the mysqli::query and mysqli::prepare methods both take their first parameter as the $query string (side note: just use the Reflection class in a quick test script to get the current method or construct prototypes. You'll find extending mysqli_result class is not actually possible, but that shouldn't be a problem here).

    Knowing that,

    1. Store the mysql query string used in the calling of your extended methods as a new property of your extended `mysqli` class
    2. Pass on the parent method's return results as normal
    3. Create a new custom method to call this string property with `explain ` prepended and run a new separate query on that using any parent method or generic Mysqli invocation. This new method will be called any time you need to output the query explanation in your html view