View and debug prepared PDO query without looking at MySQL logs

烂漫一生 提交于 2020-01-13 05:24:30

问题


I want to see what PDO is preparing without looking into the MySQL logs. Basically the final query it has built right before it executes the query.

Is there a way to do this?


回答1:


There is no built-in way to do it. bigwebguy created a function to do it 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;
}



回答2:


This is just a derivation of @Maerlyn code above which accept non-asociative arrays for params like and where if the key starts already with ':' don't add it.

/**
 * 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;
}


来源:https://stackoverflow.com/questions/6961897/view-and-debug-prepared-pdo-query-without-looking-at-mysql-logs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!