3
votes

I wanted to query only those items that have a highest likes.

This is the sql query I want to convert into CodeIgnitor's Active Records:

SELECT *, SUM(like) as totalLikes
FROM tbl_like
GROUP BY uploadID
ORDER BY totalLikes DESC
LIMIT 2

CodeIgniter:

public function get_cheezyPic(){
      $this->db->select('uploadID, SUM(like) as totalLikes');
      $this->db->from('tbl_like');
      $this->db->group_by('uploadID');
      $this->db->order_by('totalLikes DESC');
      $this->db->limit(2);

      $query= $this->db->get();

      return $query->result_array();}

But when I try to run this code, I've got this error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'like) as totalLikes FROM (tbl_like) GROUP BY uploadID ORDER BY totalLikes ' at line 1

SELECT `uploadID`, SUM(like) as totalLikes FROM (`tbl_like`) GROUP BY `uploadID` ORDER BY `totalLikes` desc LIMIT 2

What's wrong with this code?

Thanks for the help.

1

1 Answers

0
votes

This'll work for you. Please note that you were using reserved keyword so it should be enclosed with backtic ``.

public function get_cheezyPic(){
      $this->db->select('uploadID, SUM(`like`) as totalLikes',false);
      $this->db->from('tbl_like');
      $this->db->group_by('uploadID');
      $this->db->order_by('totalLikes DESC');
      $this->db->limit(2);

      $query= $this->db->get();

      return $query->result_array();
}