0

I am trying to fetch the no of records, but I am unable to write this query in yii. My sql query is given below.

select count(review) from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01')) . I am currently writing this query in yii is given below.

$results=Yii::app()->db->createCommand()
        ->Select('count(review)')
        ->from('review_business') 
        ->where('date_created'>=DATE_FORMAT(NOW() ,'%Y-11-01'))
        ->queryAll();

But I am getting this error Fatal error: Call to undefined function NOW() in G:\www\ba.dev\protected\views\business\stats.php on line 19. I am sure it is because of my poor yii query. Kindly correct my query.

2 Answers 2

1

If you are willing to run the entire query and not use the active record pattern You can try built-in YII commands to do that.

$query = 'select * from post where category=:category';
$list= Yii::app()->db->createCommand($query)->bindValue('category',$category)->queryAll();

Explanation: $query should be obvious and =:category is binding the variable category dynamically to the query for security reasons. In next line I am creating the query and substituting the value of category variable by using bindValue() function, finally queryAll retrieves all the records in the database. Hope it is clear now. In your case

$query = "select count(review) as result from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01'))" ;
$list= Yii::app()->db->createCommand($query)->queryAll();

Now you can access the result like this:

foreach ($rows as $row) {
  $result = $row["result"];
}
Sign up to request clarification or add additional context in comments.

10 Comments

How can I echo the result ? I want to show the result. So i used foreach loop like this. foreach($list as $l){echo $l;} and I got error, array to string conversion.
see my updated answer and don`t forget to include this part : select count(review) as result from .....
I am following this link, yiiframework.com/doc/guide/1.1/it/database.query-builder But i did not find the way you told me above.
oh wait a second please
Well before marking your answer correct, I want you to please explain me the above code, if you dont mind.
|
0

Try this,

$results=Yii::app()->db->createCommand()
    ->Select('count(review)')
    ->from('review_business') 
    ->where('date_created >=DATE_FORMAT(NOW() ,"%Y-11-01")')
    ->queryScalar();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.