Search code examples
phpsystemfavorites

System for keeping track of user favorites


On my website, I have a table movies and a table users

I'm trying to have an "Add to favs" button that a user can click, which will add that movie to his favorites (ajax / javascript not necessary at the moment, just php).

So what's the simplest way I could do something like that? I've thought about this but I can't seem to find a solution (all I think of is way too complicated, and in my opinion not possible).

What's your thoughts?

I don't need a ready-made script, just an idea that could get me working (although if you have an example of such script, I'd be happy to look at it).

Thanks!


Solution

  • Add a third table:

    CREATE TABLE user_favorites (
      user_id INT NOT NULL,
      movie_id INT NOT NULL,
      PRIMARY KEY (user_id, movie_id),
      FOREIGN KEY user_id REFERENCES users (user_id),
      FOREIGN KEY movie_id REFERENCES movies (movie_id)
    )
    

    This is called an intersection table or join table, as it joins rows in the users table to rows in the movies table (as you see, each column is a foreign key). It is also defines a many-to-many relationship, because one user can like many movies and one movie can be liked by many users.

    When you go to add a favorite movie for a user, all you have to do is insert a row in this table with the ID of the user and the ID of the movie:

    INSERT INTO user_favorites(user_id, movie_id) VALUES([user ID], [movie ID])
    

    To see what movies a user has favorited:

    SELECT movie_id FROM user_favorites WHERE user_id = [user ID]