Yii CDBCommand getText to show all variables in th

2019-03-27 15:05发布

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!

标签: php yii
4条回答
姐就是有狂的资本
2楼-- · 2019-03-27 15:15

Looks like you're after the PDOStatement that Yii is preparing:

$cmd = Yii::app()->createCommand();

$cmd->select("name")
       ->from('package')
       ->where('id=:id', array(':id'=>5))
       ->queryRow();

// returns a PDO Statement - http://php.net/manual/en/class.pdostatement.php
Yii::log($cmd->getPdoStatement()->queryString);

Does that work for you? Seems like it should (code untested).

查看更多
劫难
3楼-- · 2019-03-27 15:23

why don you try as below.i am not an expert just posting to my knowledge if its no suitable for your prob pardon me...

               $connection=Yii::app()->db;
            $id=5; // you can able to change by "GET" or "POST" methods
    $sql="SELECT name FROM package WHERE id = :id ";
    $command = $connection->createCommand($sql);
    $command->bindParam(":id",$id,PDO::PARAM_STR);
    $dataReader=$command->query();          
    $rows=$dataReader->readAll();
    $namevalue=array();
    foreach($rows as $max)
    {
    $namevalue = $max['name'];
    }   
    echo $namevalue; // which is the value u need

thank you...

查看更多
Root(大扎)
4楼-- · 2019-03-27 15:32

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-03-27 15:33
$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()
);
查看更多
登录 后发表回答