M
M
Maxim Lagoysky2018-09-13 11:39:09
Yii
Maxim Lagoysky, 2018-09-13 11:39:09

How to write a query if the variable is empty?

How to correctly write a query using Yii::app()->db->createCommand() if the variable in the condition may be empty?

$sql = $db->createCommand()
                ->select('`id`, `sub_id`, `min_price`,
                ->from('table')
                ->where("sub_id=$sub_id")
                ->query();

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Timofeev, 2018-09-13
@lagoy

$sql = $db->createCommand()
     ->select(['id', 'sub_id', 'min_price']),
    ->from('table');
if(!empty($sub_id)){
    $sql->where(['sub_id' => $sub_id]);
}
$sql->query();

L
Lander, 2018-09-13
@usdglander

Use filterWhere()

A
alexalexes, 2018-09-13
@alexalexes

If the where method can accept an empty string, then so be it.
The void can be different.
If you have it empty, it's '', then you need to compare like this:
$sub_id !== ''
If null, then like this
!is_null($sub_id)

A
Andrey, 2018-09-13
@VladimirAndreev

wouldn't it be easier like this:

$query = new \yii\db\Query();

$query->createCommand()->queryAll();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question