Yii CDBCommand getText to show all variables in the SQL - php

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!

$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()
);

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.

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...

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).

Related

Passing laravel eloquent query params dynamically

I have the following query params in string format
$query = '->whereIn('short_code', ["9999"])->whereBetween('request_timestamp', [request('startTime'), request('endTime')])';
How do i pass it to the eloquent? Am trying to achieve something like this
InboundMessage::query()->{$query};
Am getting the error below
Property [->whereIn('short_code', ["9999"])->whereBetween('request_timestamp', [request('startTime'), request('endTime')])] does not exist on the Eloquent builder instance.
The problem with the above query is that it looks like this
InboundMessage::query()->->whereIn('short_code', ["9999"])..
Since you have put -> in both the query builder and the $query string. So just adjust your $query to
$query = 'whereIn('short_code', ["9999"])->whereBetween('request_timestamp', [request('startTime'), request('endTime')])';
It will be something like this (not tested) using raw DB expressions:
$query = DB::table('tableName')
->whereRaw('columnName IN ["9999"] AND columnName BETWEEN value1 AND value2')
->get();

Yii2 How to get all values from column (DB)

I've been sitting for hours trying to find how to get values from table's iab_categories column category_name. I've found only the way to echo all table names:
$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tableNames = $dbSchema->getTableNames();//returns array of tbl schema's
var_export($tableNames);
Can anyone help me?
You can use query builder to do that:
$categories = (new \yii\db\Query())
->select(['category_name'])
->from('iab_categories')
->column();
The select() method sets what columns should be included in result.
The from() method sets what table should be queried.
And the column() method executes the query and return first column from result set as array.
EDIT: now, I've realized that even though you've mentioned Yii 2 in title the code you've included in question looks more like Yii 1.x.
So there is query builder version for Yii 1.x:
$categories = Yii::app()->db->createCommand()
->select('category_name')
->from('iab_categories')
->queryColumn();

How to write SQL query for yii2 ? "InnerJoin"

SQL query:
SELECT * FROM bd.group
INNER JOIN bd.account2group ON bd.group.id = bd.account2group.group_id
INNER JOIN bd.account ON bd.account2group.account_id = bd.account.id
WHERE bd.group.id = 8
How will it be in yii2?
There are multiple ways to get to this query using Yii2. You should probably be able to get to all these solutions by reading the docs. At https://www.yiiframework.com/doc/guide/2.0/en the 'Working with databases' should give you more than enough examples to get at least something working.
If you want to use the QueryBuilder from Yii2 it will look like this:
$query = (new \yii\db\Query)
->from('bd.group')
->innerJoin('bd.account2group', 'bd.group.id = bd.account2group.group_id')
->innerJoin('bd.account', 'bd.account2group.account_id = bd.account.id')
->where([
'bd.group.id' => 8,
]);
Then you can call $query->all(), $query->one(), or one of the other functions that the Query class holds. Check out https://www.yiiframework.com/doc/api/2.0/yii-db-query for all possible options.

CakePHP 3 advanced Query Not Null with strange "QueryExpression" error?

I am putting together a small mailing application within my application, and have run into a strange error - even just following the instructions for the advanced queries. I need to get -just- the mailboxes that are named:
$CoreMailboxes = TableRegistry::get('CoreMailboxes');
$query = $CoreMailboxes->find()
->where(function (QueryExpression $exp, Query $q) {
return $exp->isNotNull('name');
});
$query->hydrate(false);
return $query->toArray();
This is a near duplicate, sans "hydrate: false", of the example in the Cake Cookbook. However, it's giving me an error of
Argument 1 passed to App\Model\Table\CoreMailboxesTable::App\Model\Table\{closure}() must be an instance of App\Model\Table\QueryExpression, instance of Cake\Database\Expression\QueryExpression given
The query in the Cookbook is this:
$query = $cities->find()
->where(function (QueryExpression $exp, Query $q) {
return $exp->isNotNull('population');
});
What am I doing wrong?
You do not need to use the query expression for such a simple query..
You can just put the 'IS NOT NULL' in the where...
Now to re-use the query and create a more usable finder(), expressions may be more useful
$result = $this->Table->find()
->where([
'TableName.column_name IS NOT NULL'
])->toArray();
The problem is the instance definition's of your first argument, the doc is clear:
The passed anonymous function will receive an instance of \Cake\Database\Expression\QueryExpression as its first argument, and \Cake\ORM\Query as its second
Maybe you dont set the correct namespaces of this class, try this:
<?php
use \Cake\Database\Expression\QueryExpression as QueryExp;
//more code
//more code
->where(function (QueryExp $exp, Query $q) {
//more code
I've encounter today same error.
Try to add
use Cake\ORM\Query;
use Cake\Database\Expression\QueryExpression;
at beginning of your controller. It's help in my case.
I also try kip's answer but it doesn't work in my case

Could not include LIMIT in Axon query

I am trying to do the following query in Axon but can't make it work. Using normal query it works -
SELECT user_name, email_id FROM ors_email_user WHERE email_sent=false LIMIT 5;
In Axon, I try to do the following -
$users = new Axon('ors_email_user');
$users->load(array('email_sent=:email_sent', array(':email_sent' => false)), '', 3);
while(!$users->dry()) {
echo 'here';
}
It never goes inside the while loop. What is wrong with the query? Is there a way where I can see what query is actually being formed.
I believe the load function only allows 3 parameters to be passed, where the third is the columns that should be ordered.
You should use the find() or select() function. From the website:
find( [criteria],[order],[limit],[offset] );
select( fields,[criteria],[grouping],[order],[limit],[offset] );

Categories