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

PHP functions

How can I write a function that queries my database for a single product and returns result?

Here is what i have so far which is wrong and doesnt work:

<?php
function get_product($db, $sku) {
      $results = $db->query("SELECT name, price, img, sku, paypal FROM products WHERE product sku = '$sku'");
  } catch (Exception $e) {
      echo "data couldnt be retrieved from the database";
        return;
    }
    $products = $results->fetchALL(PDO::FETCH_ASSOC);

    return $products;
}

Kristina

Added proper markdown tags to make your code more readable.

Cheers!

thanks Shawn

2 Answers

Kristina,

I haven't used PDO as much as MySQLi, but I think for you to return just one piece of data, you would use the fetch() function instead of the fetchAll() function. Again, I've only dealt with a little bit of PDO as I prefer and use MySQLi to query databases. Hope I gave you correct information.

Cheers!

I have tried to make the code a bit refactored in my own way. Checked for hidden bugs and use a prepare statement. and made it a little clear to work with.

<?php
function get_product($db, $sku){
    try{
        $results = $db->prepare("SELECT name, price, img, sku, paypal FROM products WHERE products.sku = ?");
        $results->execute([$sku]);
        $products = $results->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        echo("Data couldn't be retrieved from the database\n");
        return;
    }
    return $products;
}

Can't say I tested it since I have no database "products". But the model should work just fine for PDO style data query.