0

We are using db2_prepare and db2_execute to prepare queries in a generic function. I am trying to have a debug method to get the full prepared query after the '?' values have been replaced by the db2_execute function.

Is there an efficient way of doing this besides manually replacing each '?' with the parameters I am passing in? i.e. is there a flag that can be set for db2_execute?

Example:

$params = array('xyz','123');
$query = "SELECT * FROM foo WHERE bar = ? AND baz = ?";
$sqlprepared = db2_prepare($CONNECTION, $query);
$sqlresults = db2_execute($sqlprepared,$params);

I would like the $sqlresults to contain the full prepared query:

"SELECT * FROM foo WHERE bar = 'xyz' AND baz = '123'";

I have looked through the docs and do not see any obvious way to accomplish this, but I imagine there must be a way.

Thank you!

2 Answers 2

1

db2_execute() does not replace parameter markers with values. Parameters are sent to the server and bound to the prepared statement there.

The CLI trace, which can be enabled on the client as explained here, will contain the actual parameter values. Keep in mind that the trace seriously affects application performance.

Sign up to request clarification or add additional context in comments.

1 Comment

Understood. I did not know that they were sent to the DB and bound on that side, I was assuming PHP handled this in the background. We were only going to be using this as a debug option on the query and having it not run by default. I am going to add an answer of what I came up with to handle this through PHP but thank you for your input!
0

I ended up writing a loop to replace the '?' parameters with a simple preg_replace after and outputting the query in my 'debug' array key:

$debugquery = $query;
foreach($params as $param) {
  $debugquery = preg_replace('/\?/',"'".$param."'",$debugquery,1);
}
return $debugquery;

This handled what I needed to do (to print the finalized query for debugging purposes). This should not be run in Production due to performance impacts but is useful to look at the actual query the server is trying to perform (if you are getting unexpected results).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.