用了一段时间的pgsql数据库,一直没搞明白怎么调试SQL,今天遇到了一段比较长的sql,然后找到一种方法,记录备用。
<?php
$sql = "SELECT * from table WHERE col_a = $1 and col_b=$2 and col_c=$3";
$params = array (42, "a string", NULL);
$debug = preg_replace_callback('/\$(\d+)\b/', function($match) use ($params) { $key=($match[1]-1); return ( is_null($params[$key])?'NULL':pg_escape_literal($params[$key]) ); }, $sql);
echo "$debug";
//prints: SELECT * from table WHERE col_a = '42' and col_b='a string' and col_c=NULL?>