Why is it that the code below only matches once, and only if the first genre_id for the movie is 1?
What is it that I've missed ?
The code with comments should say it all, but here comes my idea on how this thing works, (or at least should work)
I query a database for all available genres, and their corresponding genre_id, there are a total of 20.
Then I query the movie for genres, I have a table for joining the movie_id with the genre_id, so if the movie_id doesn't existm the movie have no genres set to it, otherwise it fetches all genre_id's set to that specific movie.
Then I loop ALL the genres through a while, when I've fetched genre_id 1 I loop the genre_id's set to the movie, ie. if the movie had genre_id's 1,5,7 set to it, it should do something like this:
are 1 the same as 1 ? = yes, set $selected
are 1 the same as 5 ? = no
are 1 the same as 7 ? = no
echo the <option>
loop again
unset $selected for next run.
are 2 the same as 1 ? = no
are 2 the same as 5 ? = no
are 2 the same as 7 ? = no
and this goes on and on until all 20 genres have been looped through the matching process.
What I don't get is that it won't match anything unless the movie has genre_id 1 set to it, and then it'll only match that one, not the rest of them.
Please help, I'm getting desperate.
<?php
if (!$movie_id) { // Checking if a movie was chosen
echo "No movie selected";
exit;
}
$query_genre = mysql_query("SELECT * FROM genre ORDER BY genre_id ASC"); // Query the database for ALL genres
$current_genre = mysql_query("SELECT genre_id FROM genre_movie WHERE movie_id=$movie_id"); // Query the selected movie for genres
if (mysql_num_rows($current_genre) == 0) { // Checking that the movie has genres set to it, if not then unset $current_genre
unset($current_genre);
}
echo "<select class=\"formfield\" name=\"genre[]\" multiple size=\"$genres\">";
while ($g_row = mysql_fetch_array($query_genre)) {
$genre_id = $g_row["genre_id"];
$genre = $g_row["genre"];
if (isset($selected)) { // Unsetting $selected for next loop
unset($selected);
}
if (isset($current_genre)) { // Only match if any genres found for the movie
while ($cg_row = mysql_fetch_array($current_genre)) {
$cgenre_id = $cg_row["genre_id"];
if ($cgenre_id == $genre_id) { // Matching the genres, if a match then set $selected
$selected = " selected";
}
}
}
echo "<option value=\"$genre_id\"$selected>$genre</option>"; // echo the currently selected genre in the while loop out
}
echo "</select>";
?>