Converting Sql query to active CodeIgniter records

I wanted to query only the items that have the highest preference.

This is the sql query I want to convert to active CodeIgnitor 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 have this error

You have an error in your SQL syntax; check the manual corresponding to your MySQL server version for the correct syntax to use next to "like" as totalLikes FROM ( tbl_like

) GROUP BY uploadID

ORDER BY totalLikes

'on 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.

+3


source to share


1 answer


This will work for you. Note that you used a reserved keyword, so it must 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();
}

      

0


source







All Articles