Debugging a MySQL Issue with PHP Using XMP instead of PRE
Published June 26th, 2009Recently, I was helping a co-worker debug a MySrQL issue with an old app that started breaking after the dev team switched the app’s textareas to TinyMCE editor. Typically, for quick-and-dirty debugging sessions that we want to wrap in minutes, we use a simple dumpQuery() function in PHP that prints out any query used in the app.
When dumping an UPDATE query we noticed thast mysql_error() was reporting that the query was breaking because one of the field appearntly had bad data — something that with CSS style-sheet data. Unfortunately, we were not looking at the actual log file that we generate from query dumps but instead we decided to be lazy and looked at the on-screen dump information shown on the browser.
Even though we were seeing mysql_error() reporting an issue with the UPDATE statement, we just could not see why the query was breaking until we decided to review our simple dumpQuery function:
function dumpQuery($query = null)
{
echo "<pre>";
print_r($query)
echo "</pre>"
}
The co-worker quickly realized that the dumpQuery() was not going to show us the actual reason for the mysql_error() on the browser because the data had HTML elements that were getting rendered by the browser; so it was causing us pull our hair out thinking why we cannot see the simple error in the UPDATE statement.
The co-worker quickly replaced the echo “<pre>” call to echo “<xmp>” and also the same for the echo “</pre>” call to echo “</xmp>”. We were immediately able to see the actual MySQL error for the UPDATE statement and fixed the field that had the TinyMCE data by calling the mysql_real_escape_string() for the data.
The “<xmp>” tag renders all HTML tags inside it, which allowed us to see the HTML elements in one of the fields being set as the problem.
Text within this tag is rendered in a monospaced font - usually Courier New. Also spaces and line breaks are preserved. The difference between this tag and PRE is that all characters (e.g. ‘<', '>‘ and ‘&’ etc.) are rendered i.e. you cannot use any other tag within XMP.
The mysql_real_escape_string() allowed us to escape the HTML elements appropriately for MySQL to handle and thus our debugging session concluded in happy ending.
We love XML tag for debugging.
Cheers.
rubayeet on September 30, 2009
Great tip! You could also try using var_dump() instead of print_r(). The later gives a formatted output and ignores to print certain PHP data types like NULL, FALSE, 0 or empty string(”). var_dump() prints everything, plus it mentions the data type and size in bytes.