Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii CDBCommand getText to show all variables in the SQL

Tags:

php

yii

I am using Yii's Yii::app()->db->createCommand() to build an SQL query. In order to view the SQL code that Yii generates, I am using the getText() method of CDBCommand. Problem is, when I use the getText() method on SQL code that contain parameters, for example:

Yii::app()->db->createCommand()
           ->select("name")
           ->from('package')
           ->where('id=:id', array(':id'=>5))
           ->queryRow();

the getText() method returns the following SQL:

select name from package where id=:id

instead of:

select name from package where id=5

This is fine for simple queries, but for more complex queries with lots of parameters, it is quite a pain to copy/paste each parameter into the SQL code to test it.

Is there any way to display the parameters directly inside the SQL using getText() or some other method in Yii?

Cheers!

like image 571
Bug Magnet Avatar asked Feb 10 '12 10:02

Bug Magnet


2 Answers

$sql = Yii::app()->db->createCommand()
  ->select("name")
  ->from('package')
  ->where('id=:id', array(':id'=>5))
  ->queryRow();

$query=str_replace(
   array_keys($sql->params),
   array_values($sql->params),
   $sql->getText()
);
like image 110
The247 Avatar answered Nov 14 '22 14:11

The247


You can use the CDbConnetion::enableParamLogging propery. For instance, in config/main.php:

'db' => array (
        'enableParamLogging' => true,

and the shown and logged error will contain the bound values.

like image 2
Santilín Avatar answered Nov 14 '22 14:11

Santilín