我想看看PDO正在准备什么而不查看MySQL日志。基本上是它在执行查询之前构建的最终查询。
有办法做到这一点吗?
答案 0 :(得分:4)
没有内置的方法可以做到这一点。 bigwebguy创建了一个功能in one of his answers:
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* @param string $query The sql query with parameter placeholders
* @param array $params The array of substitution parameters
* @return string The interpolated query
*/
public static function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}
答案 1 :(得分:0)
这只是@Maerlyn代码的派生,上面的代码接受参数的非关联数组,例如,如果键已经以':'开头,则不要添加。
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* @param string $query The sql query with parameter placeholders
* @param array $params The array of substitution parameters
* @return string The interpolated query
*
* @author maerlyn https://stackoverflow.com/users/308825/maerlyn
*/
function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
if (!isAssoc($params)){
$_params = []; // associative array
foreach($params as $param){
$key = $param[0];
$value = $param[1];
// $type = $param[2];
$_params[$key] = $value;
}
$params = $_params;
}
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/'.((substr($key,0,1)==':') ? '' : ':').$key.'/';
} else {
$keys[] = '/[?]/';
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}