This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Now that you’ve had a chance to try this for yourself, I’m going to show you how I solved this challenge. When it comes to programming, there is alway more than one way to do something. If you solved this challenge in a different way than what I am going to show you, GREAT! Now you’ll have two ways to accomplish this and will be able to compare those two options when you run into other similar situations.
Example Code
functions.php
function genre_array($category = null) {
$category = strtolower($category);
include("connection.php");
try {
$sql = "SELECT genre, category"
. " FROM Genres "
. " JOIN Genre_Categories "
. " ON Genres.genre_id = Genre_Categories.genre_id ";
if (!empty($category)) {
$results = $db->prepare($sql
. " WHERE LOWER(category) = ?"
. " ORDER BY genre");
$results->bindParam(1,$category,PDO::PARAM_STR);
} else {
$results = $db->prepare($sql . " ORDER BY genre");
}
$results->execute();
} catch (Exception $e) {
echo "bad query";
}
$genres = array();
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
$genres[$row["category"]][] = $row["genre"];
}
return $genres;
}
suggest.php
<select name="genre" id="genre">
<option value="">Select One</option>
<?php
$genre_array = genre_array();
foreach ($genre_array as $category=>$options) {
echo "<optgroup label=\"$category\">";
foreach ($options as $option) {
echo "<option value=\"$option\"";
if (isset($genre) && $genre==$option) {
echo " selected";
}
echo ">$option</option>";
}
echo "</optgroup>";
}
?>
</select>
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up