How to count my likes

I mean my like and dislike API is almost complete but I don’t know how to count my likes

private function Likes(){
			if($this->get_request_method() != "POST"){
			$userId= $this->_request['userId'];
			$postid= $this->_request['postid'];
			$status= $this->_request['status'];
			$sql = mysql_query("SELECT * from likes Where userId='".$userId."' AND postid='".$postid."'", $this->db);
			if(mysql_num_rows($sql) > 0){
			$result = array();
			$rlt = mysql_fetch_array($sql,MYSQL_ASSOC);
				if($rlt['status']== 1){
				$sql = mysql_query("UPDATE `likes`
							status= 0
							WHERE userid = '".$userId."' AND postid= '".$postid."'", $this->db);
							$success = array('status' => 0, "msg" => "Dislike");	
				elseif($rlt['status']== 0){
				$sql = mysql_query("UPDATE `likes`
							status= 1
							WHERE userid = '".$userId."' AND postid= '".$postid."'", $this->db);
							$success = array('status' => 1, "msg" => "Like");	
			$sql = mysql_query("insert into `likes` set 
				`status`='".$status."'", $this->db);
			$success = array('status' => 1,"msg" => "Like");	
					$this->response($this->json($success), 200);
				// If success everythig is good send header as "OK" and return list of users in JSON format

It’s a bit difficult to suggest how you might count “likes” without knowing how the database is configured, and exactly what you want to count. For example the first query returns likes for a specific user id and post id, so you have a count of those. Or do you want all the likes for a user (in which case, the same query but without the post id) or something else?

Also, if this is code you are developing now (you say it’s almost complete), drop the old mysql_ calls as they are no longer part of the PHP language. Use mysqli or PDO instead.


we click to like so status 1 is shown and now the second click so status is 0 but how to count my likes,

Well, that didn’t really clarify how you define “my” likes - all likes for a given user_id?

select count(*) from likes where user_id = :userid and status=1

would do that. I’m not sure why you don’t delete the “like” rather than setting the status to zero when it is disliked, but I don’t know your system.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.