ralston3
ralston3

Reputation: 53

Vote Up/Like System for posts using MySQL

I've searched for this on stackoverflow and while I've found something along these lines, I haven't found anything that really helps me, so I'll ask the question myself.

So I'm trying to implement a like button for images on my site. But I'm having a little trouble figuring out how it goes.

So far, I have this on the SQLI side of things :

CREATE TABLE if not exists `likes` (
         `id` int(11) NOT NULL AUTO_INCREMENT,
         `image_id` varchar(300) NOT NULL,
         `liker_username` varchar(50) NOT NULL,
          `liked_unliked` enum('0','1') NOT NULL, DEFAULT '0'
           PRIMARY KEY (`id`)
        );

Where id is the id of the like, image_id is the id of the image being liked, liker_username is the username of the user clicking the like button, liked_unliked is whether or not that user has liked the image (1 for liked, 0 for unliked [to make sure users only vote once]).

I have the image_id already stored in a photos table.

I've been told to put a unique index on liker_username and image_id in order to prevent users from liking an image multiple times, but I just want a second opinion.

So...is what I have so far even correct? Like I said, I'm trying to get it so that users can click the like button and like the image, but only once. Any help is appreciated. Thanks

Upvotes: 4

Views: 221

Answers (1)

Andrew
Andrew

Reputation: 20111

Looks like you're on the right track.

Like another user said, you might consider having a users table with user data and ids, and put the foreign key liker_user_id in your likes table. Your image id could also be a foreign key, with images stored in an images table.

You may consider allowing anonymous votes, one per i address, adding the ip address to the DB if the user is not logged in. You can get the users ip address with:

$_SERVER['REMOTE_ADDR'];

Upvotes: 1

Related Questions