Doctrine - How to print out the real sql, not just

2019-01-08 05:34发布

We're using Doctrine, a PHP ORM. I am creating a query like this:

$q = Doctrine_Query::create()->select('id')->from('MyTable');

and then in the function I'm adding in various where clauses and things as appropriate, like this

$q->where('normalisedname = ? OR name = ?', array($string, $originalString));

Later on, before execute()-ing that query object, I want to print out the raw SQL in order to examine it, and do this:

$q->getSQLQuery();

However that only prints out the prepared statement, not the full query. I want to see what it is sending to the MySQL, but instead it is printing out a prepared statement, including ?'s. Is there some way to see the 'full' query?

15条回答
forever°为你锁心
2楼-- · 2019-01-08 06:06

An example..

$qb = $this->createQueryBuilder('a');
$query=$qb->getQuery();

Show SQL: $sql=$query->getSQL();

Show Parameters: $parameters=$query->getParameters();

查看更多
Explosion°爆炸
3楼-- · 2019-01-08 06:06

You can easily access the SQL parameters using the following approach.

   $result = $qb->getQuery()->getSQL();

   $param_values = '';  
   $col_names = '';   

   foreach ($result->getParameters() as $index => $param){              
            $param_values .= $param->getValue().',';
            $col_names .= $param->getName().',';
   } 

   //echo rtrim($param_values,',');
   //echo rtrim($col_names,',');    

So if you printed out the $param_values and $col_names , you can get the parameter values passing through the sql and respective column names.

Note : If $param returns an array, you need to re iterate, as parameters inside IN (:?) usually comes is as a nested array.

Meantime if you found another approach, please be kind enough to share with us :)

Thank you!

查看更多
仙女界的扛把子
4楼-- · 2019-01-08 06:06

You can use :

$query->getSQL();

If you are using MySQL you can use Workbench to view running SQL statements. You can also use view the running query from mysql by using the following :

 SHOW FULL PROCESSLIST \G
查看更多
冷血范
5楼-- · 2019-01-08 06:06
$sql = $query->getSQL();

$parameters = [];
    foreach ($query->getParameters() as $parameter) {
        $parameters[] = $parameter->getValue();
    }

$result = $connection->executeQuery($sql, $parameters)
        ->fetchAll();
查看更多
趁早两清
6楼-- · 2019-01-08 06:07

Doctrine is not sending a "real SQL query" to the database server : it is actually using prepared statements, which means :

  • Sending the statement, for it to be prepared (this is what is returned by $query->getSql())
  • And, then, sending the parameters (returned by $query->getParameters())
  • and executing the prepared statements

This means there is never a "real" SQL query on the PHP side — so, Doctrine cannot display it.

查看更多
乱世女痞
7楼-- · 2019-01-08 06:11

To print out an SQL query in Doctrine, use:

$query->getResult()->getSql();
查看更多
登录 后发表回答