What I am looking for is a php function that takes an unformatted query like this:
$sql = "select name, size from things where color = 'green' order by price asc";
so that it would appear in an HTML page something like this:
SELECT name, size FROM things WHERE color = 'green' ORDER BY price ASC';
There's some code inside phpMyAdmin that does this already, I could look in there I guess!
I had the same problem and made a light-weight PHP class to do formatting/syntax highlighting.
https://github.com/jdorn/sql-formatter
I haven't fully tested it with complex queries (sub-selects, unions, etc.), but it seems to work pretty well for common cases.
To get fully accurate results, you really need a full SQL parser like phpMyAdmin uses, but that uses 10,000+ lines of code spread out over many files and is probably overkill for simple debugging.
Using phpMyAdmin is quite straight forward:
Add a stylesheet to enable syntax highlighting. If you read a bit in the sqlparser documentation you'll find some other function for different formatting types.
Only thing is that phpMyAdmin is somewhat large to only use SQL parsing, so you might want to strip all other functionalities...
I don't think there's any freely available code that does this within PECL or similar - which is a pity, as it would be quite a neat little utility. (Albeit only with fairly limited uses.)
As such, you're answered you own question - phpMyAdmin is probably a good first port of call.
Something like this will work - add any other SQL keywords you want to parse:
May be This is what you want: http://www.orczhou.com/sqlparser/ PHP SQL Format