mysql - How to display the most liked post when the likes are stored in another table php -
i developing small cms, posts have likes. store likes in table liked posts can found in users 'dashboard'.
"likes" table
» likes - id - user - post - timestamp
but show liked posts in page. how achieve that?
first make function details of post
public function get_post_details(){ $sql = 'select pt.id, pt.details <- (you can select whatever want display) '; $sql .= 'from post_table pt '; $query = $this->db->query($sql); $result = $query->row(); foreach ($result $key => $value) { $result->post_likes = $this->get_post_likes_by_id($result->id); } return ( $query->num_rows() ) ? $result : false; }
then make second function likes in like_table assuming every post of user add 1 row in table this
if first_user likes post1 table of likes store data this
likes_table id post_id user_likes 1 1 1
then second user user likes post1 should this
likes_table id post_id user_likes 1 1 1 2 1 2
user_likes id of user likes post
second function
public function get_post_likes_by_id($post_id) { $params = []; $sql = 'select count(lt.id) total_likes '; $sql .= 'from likes_table lt '; $sql .= 'where lt.post_id = ? '; $params[] = $post_id; $query = $this->db->query($sql, $params); $likes = $query->result(); $data = []; foreach ($likes $like) { array_push($data, $like->total_likes); } return $data; }
Comments
Post a Comment