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 trial

PHP

Kyle B
Kyle B
6,383 Points

try/catch block for product size is failing, and I can't figure out why

Below is my code for get_product_single()

The problem appears to be in my second try/catch block, where the JOIN occurs, but it is identical to the walkthrough. Any idea what I'm doing wrong?

function get_product_single($sku) { require(ROOT_PATH . "inc/database.php");

try {
    $results = $db->prepare("SELECT name, price, img, sku, paypal FROM products WHERE sku = ?");
    $results->bindParam(1, $sku);
    $results->execute();
}   catch (Exception $e) {
    echo "Data could not be retrieved from database.";
    exit;
}

$product = $results->fetch(PDO::FETCH_ASSOC);
if ($product === false) return $product;

$product["sizes"] = array();

try {
    $results = $db->prepare("
        SELECT size 
        FROM product_sizes ps 
        INNER JOIN sizes s ON ps.size_id = s.id
        WHERE product_sku = ?
        ORDER BY `order`");
    $results->bindParam(1,$sku);
    $results->execute();

} catch (Exception $e) {
        echo "data couldn't be retrieved";
        exit;
}
while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
    $product["sizes"][] = $row["size"];
}

return $product;

}

Vicente Armenta
Vicente Armenta
11,037 Points

Hello, it would be more helpful if you just throw the error on your second try, something like:

catch (Exception $e) {
        echo "Error: ".$e;
        exit;
}

or even

catch (Exception $e) {
        exit("Error: ".$e);
}