How to print the SQL statement that is being sent to the database?

Asked

Viewed 640 times

6

I would like to know how to printout an SQL for the purpose of controlling 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 database?

2 answers

12

Thus

echo $sql ->queryString

7


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

<?php

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');

        $this->setplaceHolder($query);
        $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 method setValues() works as follows first find out what kind of markup is a question mark(?) or a name(:param), array_fill() create an array where the elements are the regex of the markups(/\?/ or /:[a-z0-9_]+/i) afterward 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.