Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IFNULL(COUNT('id'),0) in Codeigniter

Tags:

codeigniter

I believe there is an error in this line in Codeigniter using Active Records, but I cant seem to figure out the syntax on the second line with IFNULL() and COUNT()

$this->db->select('places.*, category.*')
            ->select('IFNULL(COUNT("places_reviews.place_id"), 0) AS num_reviews')
            ->from('places')
            ->join('category', 'places.category_id = category.category_id')
            ->join('places_reviews', 'places_reviews.place_id = places.id', 'left')
            ->where('places.category_id', $category_id)
            ->group_by('places.id')
            ->limit($limit, $offset)
            ->order_by($sort_by, $sort_order);
like image 204
Nyxynyx Avatar asked May 09 '11 17:05

Nyxynyx


People also ask

What is Ifnull function in MySQL?

MySQL IFNULL() Function The IFNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.

Is null in CI?

Value IS NOT NULL in codeigniter.


1 Answers

Add false after the SELECT statement. CodeIgniter is trying to escape the statement with backticks and doesn't know how to do so correctly. The false will tell it not to.

->select('IFNULL(COUNT(`places_reviews.place_id`), 0) AS `num_reviews`', false)

EDIT: In COUNT("places_reviews.place_id"), the quotes should be backticks.

like image 155
Rocket Hazmat Avatar answered Dec 07 '22 17:12

Rocket Hazmat