NotionCommotion Posted June 26, 2019 Share Posted June 26, 2019 (edited) I've used a showQuery() method for years which accepted a SQL string and data array. Sometimes, I just have the PDO statement and I need to add temporary script just to keep track of the SQL string. Was looking at debugDumpParams() today which prompted me to create the new showStmtQuery() method. My approach of extracting the table from debugDumpParams's printed results is a little clunky. Any recommendations? Could/should other information from debugDumpParams's output be used? I typically don't use bound parameters but know I should more often. Suggestions how this could be changed to work with bound parameters? Thanks function showQuery(string $sql, arrray $data, bool $keepLineBreaks=false):string { $keys = []; $values = []; foreach ($data as $key=>$value) { $keys[] = is_string($key)?'/:'.$key.'/':'/[?]/'; $values[] = is_numeric($value)?$value:"'$value'"; } $sql = preg_replace($keys, $values, $sql, 1, $count); return $keepLineBreaks?$sql:str_replace(array("\r", "\n"), ' ', $sql); } function showStmtQuery(\PDOStatement $stmt, array $data, bool $keepLineBreaks=false):string { ob_start(); $stmt->debugDumpParams(); $sql = ob_get_contents(); ob_end_clean(); //$sql = strtok(substr($sql, strpos($sql, '] ')+2), "\n"); $start=strpos($sql, '] ')+2; $sql = substr($sql, $start, strpos($sql, "\nParams:") - $start); return showQuery($sql); } $data=[5,50]; $sth = $pdo->prepare('SELECT * FROM my_table WHERE id > ? AND id < ?'); echo(showStmtQuery($sth, $data).PHP_EOL); //SELECT * FROM my_table WHERE id > 5 AND id < 50 $data=['lowId' => 5, 'highId' => 50]; $sth = $pdo->prepare('SELECT * FROM my_table WHERE id > :lowId AND id < :highId'); echo(showStmtQuery($sth, $data).PHP_EOL); //SELECT * FROM my_table WHERE id > 5 AND id < 50 Edited June 26, 2019 by NotionCommotion Changed to use original showQuery function Quote Link to comment Share on other sites More sharing options...
Barand Posted June 26, 2019 Share Posted June 26, 2019 Instead of ... ob_start(); $stmt->debugDumpParams(); $sql = ob_get_contents(); ob_end_clean(); //$sql = strtok(substr($sql, strpos($sql, '] ')+2), "\n"); $start=strpos($sql, '] ')+2; $sql = substr($sql, $start, strpos($sql, "\nParams:") - $start); why don't you use ... $sql = $stmt->queryString; 1 Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted June 26, 2019 Author Share Posted June 26, 2019 2 minutes ago, Barand said: Instead of ... why don't you use ... $sql = $stmt->queryString; Because I either didn't know or forgot about it. Thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.