How can I make a like button, that show who has liked my post, on a social network?

Dani AI

Generated

For : if the likes are for your own site (as asked), build them into your app. If you only need counts from external networks, use their widgets (as noted). Below is a compact, production-minded pattern for PHP + MySQL that records likes, lets a user toggle a like, and returns both the count and a list of who liked a post.

Minimal database (add foreign keys to your users/posts tables as appropriate):

CREATE TABLE likes (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  post_id INT UNSIGNED NOT NULL,
  user_id INT UNSIGNED NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY ux_post_user (post_id, user_id),
  INDEX idx_post (post_id)
) ENGINE=InnoDB;

Server-side pattern (PDO, short version): toggle a like, then return new count and a small list of likers.

$stmt = $pdo->prepare('SELECT 1 FROM likes WHERE post_id=? AND user_id=?');
$stmt->execute([$post,$user]);
if ($stmt->fetch()) {
  $pdo->prepare('DELETE FROM likes WHERE post_id=? AND user_id=?')->execute([$post,$user]);
} else {
  $pdo->prepare('INSERT INTO likes (post_id,user_id) VALUES (?,?)')->execute([$post,$user]);
}
$count = $pdo->prepare('SELECT COUNT(*) FROM likes WHERE post_id=?')->execute([$post])->fetchColumn();
$likers = $pdo->prepare('SELECT u.id,u.username FROM likes l JOIN users u ON u.id=l.user_id WHERE l.post_id=? ORDER BY l.created_at DESC LIMIT 10');
$likers->execute([$post]);

Frontend and operational notes: call the toggle endpoint with fetch/AJAX and update the button state plus the visible count. Show a short list (top 5–10) and a “view all” modal that pages results. Important cautions: use prepared statements, CSRF tokens, and a UNIQUE constraint to avoid duplicate likes; add an index on post_id for fast counts; consider maintaining a denormalized likes_count on posts for large scale and update it atomically; paginate the likers list; respect privacy settings (some users may hide their likes); sanitize all output to prevent XSS.

Recommended Answers

All 4 Replies

You'll have to tell more such as is this your site, on Faceobok, Tweeter or other?

Your site would have you implement it. Other sites? I'm going with no.

There’s a snippet of Javascript you can put on your site to show how many Facebook likes it got, how many Tweets, etc.

I’m on my cell now not near my computer but I’ll find specific code for you a bit later.

Glad to hear you got it working. I'll mark this question solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.