How to make PHP likes

Create likes using PHP w/ an example: Learn to use PHP to create likes using a simple example code.

PHP Likes

In web programming, likes are a way to allow users to express their opinions on various content. A like can be thought of as a digital “thumbs up” and can be used to measure the popularity of content. In this tutorial, we'll show you how to create a like system in PHP.

First, we need to create a database table to store the likes. We'll call it “likes” and it will have two columns: “user_id” and “content_id”. The “user_id” column will contain the ID of the user who liked the content, and the “content_id” column will contain the ID of the content that was liked. Here’s the SQL code for creating the table:


CREATE TABLE likes (
  user_id int NOT NULL, 
  content_id int NOT NULL
);

Next, we need to create a function that will allow us to “like” content. This function will take two parameters: the user’s ID and the content’s ID. It will then insert a new row into the “likes” table with those two IDs. Here’s the code:


function like($user_id, $content_id) {
  $sql = "INSERT INTO likes (user_id, content_id) VALUES (?, ?)";
  $stmt = $db->prepare($sql);
  $stmt->bind_param("ii", $user_id, $content_id);
  $stmt->execute();
}

Now that we have a way to “like” content, we need a way to “unlike” content. This function will take two parameters: the user’s ID and the content’s ID. It will then delete the row from the “likes” table with those two IDs. Here’s the code:


function unlike($user_id, $content_id) {
  $sql = "DELETE FROM likes WHERE user_id = ? AND content_id = ?";
  $stmt = $db->prepare($sql);
  $stmt->bind_param("ii", $user_id, $content_id);
  $stmt->execute();
}

Finally, we need a way to check if a user has already liked a particular piece of content. This function will take two parameters: the user’s ID and the content’s ID. It will then check if there is a row in the “likes” table with those two IDs. If there is, it will return true, otherwise it will return false. Here’s the code:


function has_liked($user_id, $content_id) {
  $sql = "SELECT * FROM likes WHERE user_id = ? AND content_id = ?";
  $stmt = $db->prepare($sql);
  $stmt->bind_param("ii", $user_id, $content_id);
  $stmt->execute();
  return $stmt->affected_rows > 0;
}

And that’s it! We’ve now created a basic PHP like system. You can use the functions we’ve created to allow users to “like” and “unlike” content, as well as to check if a user has already liked a particular piece of content.

Answers (0)