Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP to format an input SQL query as HTML?

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!

like image 617
Simon Nuttall Avatar asked Jan 16 '10 19:01

Simon Nuttall


1 Answers

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.

like image 112
Jeremy Dorn Avatar answered Oct 07 '22 11:10

Jeremy Dorn