Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEric Schroeder
19,894 PointsThe function did not echo "bad query" within the select tag.
When I ran this for the first time I had a typo in the query and the page would not display any html after the genre drop down. It also didn't display the text "bad query". If I ran the function outside of the select tag it would give me the "bad query" message. Is there a way to display this error within the select tag as intended? If the database was not available it would be nice to relay that message to the user instead of the page not fully loading.
1 Answer
Unsubscribed User
8,428 PointsI realize this is a fairly old question but I took a stab at it. It seems that to do what you suggest and create output for a user to see you would need to setup your logic to include html output in the try block for successful queries as well as setup some html in your catch block to display any message you would want to give to a user.
<?php
try{
$result = $db->prepare("
SELECT genre
FROM genres
JOIN genre_categories ON genres.genre_id=genre_categories.genre_id
WHERE category = ?;
");
$result->bindParam(1, $category, PDO::PARAM_STR);
$result->execute();
foreach($result as $item){
$genreitem = $item['genre'];
$categories = "<option value=\"$genreitem\"";
if (isset($genre) && $genre==$genreitem) {
$categories .= " selected";
}
$categories .= ">$genreitem</option>";
echo $categories;
}
}catch (Exception $e) {
$genreitem = "Sorry, something went wrong and we could not find our categories.";
$categories = "<option value=\"$genreitem\"";
if (isset($genre) && $genre==$genreitem) {
$categories .= " selected";
}
$categories .= ">$genreitem</option>";
echo $categories;
}