views:

85

answers:

2

I'm trying to update the database library that we use at work to use parameterized queries so that coworkers who are not very knowledgeable about SQL injection won't have to remember to escape input and just pass in an array of parameters instead (I'm using pg_query_params).

However, I am running into a problem. One of the requirements of the database library is that it logs each query that is executed and I can't figure out a way to get the text of a parameterized query once the parameters have been filled in. Is there any way to do this (aside from rolling my own function for parameterized queries, I guess)?

In other words, when executing a parameterized query like

pg_query_params('SELECT id FROM table WHERE foo = $1', array('bar'));

I want to get something like

SELECT id FROM table WHERE foo = 'bar'
+1  A: 

PostgreSQL extended protocol (which is used by pg_query_params) separates parameters from queries.

The queries are ultimately constructed only on the server side, there is no way to construct them on the client side using only PostgreSQL's capabilities.

You can substitute the values of the parameters provided and log the query before sending the params using preg_replace.

Update:

You can enable PostgreSQL logging which will log the queries into a file or syslog (including bound parameters) on the server side, then periodically load this file into a PostgreSQL table.

Quassnoi
Is there no way to get the last executed query from postgres? I could use `preg_replace` or the like, but then I'd need to deal with quoting and escaping manually anyways.
Daniel Vandersluis
This doesn't exactly solve my problem because I need to be able to output the query with the rest of the page, but I have accepted it because it does answer the question.
Daniel Vandersluis
A: 

Unless you can replace every occurrence of pg_query_params() in your source code with your own wrapper function (if you can, then you might want to use the auto prepend functionality in PHP to include the declaration of the wrapper) then you can only really do this at the database level.

C.

symcbean