M
M
morricone852017-06-13 20:35:26
Yii
morricone85, 2017-06-13 20:35:26

Prepared queries in yii2?

Hello! There is this code:

$where = ''; 
       if(!empty($filter_time)) $where =" and date_created > now()-Interval <b>$filter_time </b>          minute ";
       if(!empty($filter_category))
       $where.= "and path LIKE '<b>$filter_category</b>%' "; 
      
       $sql = Yii::$app->db->createCommand("SELECT COUNT(*) FROM Pages
       JOIN categories ON categories = id_categories WHERE status = 1 $where")->queryScalar();

How to spell correctly bindValues().

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
latteo, 2017-06-13
@morricone85

Try like this:

$where = ''; 
if(!empty($filter_time)) $where =" and date_created > now()-Interval :filter_time minute ";
if(!empty($filter_category))
$where.= "and path LIKE ':filter_category%' "; 

$sql = Yii::$app->db->createCommand("SELECT COUNT(*) FROM Pages
JOIN categories ON categories = id_categories WHERE status = 1 $where")
  ->bindValue(':filter_time', $filter_time)
  ->bindValue(':filter_category', $filter_category)
  ->queryScalar();

M
Maxim Fedorov, 2017-06-15
@qonand

Why are you working with the Command class? by doing this, you only create difficulties for yourself ... to create complex queries in yii there is a Query class that perfectly solves your problem, for example like this:

$query = new \yii\db\Query();
$query->from('Pages')
    ->leftJoin('categories', ['categories' => 'id_categories'])
    ->where(['status' => 1])
    ->andFilterWhere(['like', 'path', $filter_category]);
if (! empty($filter_time)) {
    $expression = new \yii\db\Expression('now() - interval :filter_time minute', [
        ':filter_time' => $filter_time
    ]);
    $query->andWhere(['>', 'date_created', $expression]);
}

M
Maxim Timofeev, 2017-06-13
@webinar

Есть такой код
kill whoever wrote it.
Why use a framework if you don't use AR and its other goodies?
Example from the docs:

$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=:id AND status=:status')
           ->bindValue(':id', $_GET['id'])
           ->bindValue(':status', 1)
           ->queryOne();

link to docs in Russian: https://nix-tips.ru/yii2-api-guides/guide-ru-db-da...
link to docs in English: www.yiiframework.com/doc-2.0/guide- db-dao.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question