Retrieve (or simulate) full query from PDO prepared statement

后端 未结 5 1671
孤城傲影
孤城傲影 2020-12-01 14:50

I stumbled upon this question from two years ago.

Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepare

5条回答
  •  离开以前
    2020-12-01 15:28

    The following static method takes a PDO query template (an SQL query with ? and/or :name placeholders) and interpolates the parameters:

    static public function getDebugFullQuery($query, $params = array()){
        if(is_array($params) && count($params)){
    
            $search = [];
            $replace = [];
    
            foreach($params as $k => $p){
                $pos = strpos($query, ":{$k}");
                if($pos !== false){
                    $query = substr($query, 0, $pos) . "%!-!{$k}!-!%" . substr($query, $pos + strlen($k) + 1);
                }
                else {
                    $pos = strpos($query, "?");
                    if($pos !== false){
                        $query = substr($query, 0, $pos) . "%!-!{$k}!-!%" . substr($query, $pos + 1);
                    }
                    else {
                        break;
                    }
                }
    
                $search[] = "%!-!{$k}!-!%";
                $replace[] = "'" . str_replace(array("\r", "\n", "'"), array("\\\\r", "\\\\n", "\\'"), $p) . "'";
            }
    
            if(count($search)){
                $query = str_replace($search, $replace, $query);
            }
        }
    
        return $query;
    }
    

    As indicated by the method name, you should use this for debugging purposes only.

提交回复
热议问题