SQL parser in PHP?

From: Date: Wed, 30 Apr 2003 15:55:46 +0000
Subject: SQL parser in PHP?
Groups: php.general 
Request: Send a blank email to php-general+get-145806@lists.php.net to get a copy of this message
I'm trying to put together an auditing system for the SQL queries my application will be running. I figured the easy way to handle this was to write a small parsing function that could take a query string, and work out UPDATE/DELETE/SELECT/INSERT, and the appropriate fields, values and keys. It would then generate the appropriate insert lines based on that information and execute the inserts. I managed to do the UPDATE part easily, as the fields are in a pretty easy format to deal with. Well, some of the update part at least, I just managed to fool it. To save myself a lot of grief, does a SQL parsing engine of the type I'm describing already exist? Code as stands: $query = "UPDATE sometable SET somefield=somevalue, someotherfield='some, othervalue' WHERE somekey=somekeyvalue AND someotherkey='someotherkeyvalue'"; if (preg_match("/^UPDATE /i", $query) ) { if (preg_match("/UPDATE (\w+) SET (.*) WHERE (.*)/", $query, $matches)) { // Full string match is in 0 // Table is in 1 // Modified fields are in 2 // Keys are in 3 // Parse out multiple fields being updated. if (preg_match("/'?, /", $matches[2])) { $pairs = preg_split ("/,\s?/", $matches[2]); foreach ($pairs as $key => $value) { preg_match("/^(\w+)='?(\w+)'?/", $value, $matches2); $fields[$key] = $matches2[1]; $values[$key] = $matches2[2]; } } else { preg_match("/^(\w+)='?(\w+)'?/", $value, $matches2); $fields[$key] = $matches2[1]; $values[$key] = $matches2[2]; } foreach ($fields as $kk => $vv) { echo "INSERT INTO audit (audittime, field, value) VALUES (now(), '$vv', '$values[$kk]')\n"; } } } /usr/local/php4/bin/php index.php INSERT INTO audit (audittime, field, value) VALUES (now(), 'somefield', 'somevalue') INSERT INTO audit (audittime, field, value) VALUES (now(), 'someotherfield', 'some') INSERT INTO audit (audittime, field, value) VALUES (now(), '', '') ^-- broken output due to the comma and space in the otherfield value area.

« previous php.general (#145806) next »