How to print the SQL statement being sent to the bank?


I would like to know how to write a SQL for control purposes of the statement being sent to the database:

$sql = $pdo->query("SELECT * FROM imovel WEHRE CATEGORIA = 'APARTAMENTO'");

How to print the SQL statement being sent to the bank?

asked by anonymous 03.10.2014 / 18:34

2 answers


Based on this question , I created a class to see the values of a prepared statement, basically replacing the placholders by the values. In the example is shown how to call the class.


class queryDebugger{
    const QUESTION_MARK = '/\?/';
    const NAMED_PLACE_HOLDER = '/:[a-z0-9_]+/i';

    private $placeHolder;

    public function setValues($query, $values){

        if(count($values) == 0)  throw new exception('Empty values');

        $placeHolder = array_fill(0, count($values), $this->placeHolder);
        preg_match_all($this->placeHolder, $query, $queryPlaceHolders);

        if(count($placeHolder) != count($queryPlaceHolders[0])){
            throw new exception ('The number of placeholders does not match with values in: ' .$query. ' values: '.count($placeHolder));

        $newQuery = preg_replace($placeHolder, $values, $query, 1);

        return $newQuery;

    private function setPlaceHolder($query){
        (preg_match(queryDebugger::QUESTION_MARK, $query)) ? 
           $this->placeHolder = queryDebugger::QUESTION_MARK :
           $this->placeHolder = queryDebugger::NAMED_PLACE_HOLDER;


The setValues() method works as follows first find the type of markup if it is an interrogation ( ? ) or a name ( :param ), array_fill () creates an array where elements are the regex of markings ( /\?/ or /:[a-z0-9_]+/i ) then preg_match_all returns an array (third parameter) of all occurrences found in $query .

 $newQuery = preg_replace($placeHolder, $values, $query, 1);

preg_replace () replaces the markings with their values the number one (last parameter) is the limit of substitutions that must be made.

03.10.2014 / 19:26


echo $sql ->queryString
03.10.2014 / 18:36