Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The best way I can think of is to have a <em>many-to-many relationship</em> between genres and movies (meaning a movie can have multiple genre and one genre can appear on many movies).</p> <p>This involves adding two more tables, one to define the genres, and one to associate them with movies:</p> <pre><code>genres --------- id | name </code></pre> <p>Here's the slightly tricky part:</p> <pre><code>genres-movies ------------------- movie_id | genre_id </code></pre> <p>Where <code>movie_id</code> is an actual ID from the <code>movies</code> table, and <code>genre_id</code> is an actual ID from the <code>genres</code> table.</p> <p>For instance, genre with the ID of 1 is <code>Science Fiction</code>, and the movie with the ID of 42 is <code>Hitchhiker's Guide to the Galaxy</code> (see what I did there?), this means that if I have the entry <code>42 | 1</code> at the <code>genres-movies</code>, will mean that Hitchiker's Guide to the Galaxy is a Science Fiction. Note that neither <code>movie_id</code> nor <code>genre_id</code> are unique, both can appear multiple times, so the following is possible:</p> <pre><code>movie_id | genre_id ---------+--------- 1 | 2 1 | 3 2 | 2 3 | 1 </code></pre> <p>To find all the genres of a movie:</p> <pre><code>SELECT `genre_id` FROM `genres-movies` WHERE `movie_id` = &lt;ID&gt;; </code></pre> <hr> <p>After all the background, to your question. With that approach, you need multiple queries, remove all genres from a movie, then each to add the ones you selected. You have to do that because checkboxes that were not selected are not sent to the server (pseudo code)</p> <pre><code>DELETE FROM `genres-movies` WHERE `movie_id` = &lt;ID&gt;; --Remove all genres foreach ($genres_from_checkboxes as $genre) { INSERT INTO `genres-movies` (`movie_id`, `genre_id`) VALUES (:movie_id, :genre_id) } </code></pre> <p><strong>NOTE!</strong> Always sanitize (or better yet <em>prepare!!!</em>) queries with data that came from the user!</p> <p>Phew! That was long, hope you learned a thing or two :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload