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

Questions about php codes.

I have some questions about some codes in a function. What do " ORDER BY order" and " $product["sizes"][] = $row["size"]" mean?

The code of the function is as follows:

 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 the database.";
      exit;
    }

    $product=$results->fetch(PDO::FETCH_ASSOC);
    if ($product===false)return $product;
    $product["sizes"]=array();
    try{
        $results=$db->prepare("
        SELECT size
        FROM products_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 could not be retrieved from the database.";
        exit;
    }
    while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
        $product["sizes"][] = $row["size"];
    }

    return $product;
}

Hey Kohane Kagami , ORDER BY used to set the order of retreive data from database in Ascending or Descending order.If you simply write 'ORDER BY order' retreive data will be in Ascending order by default.

And here,

  while ($row = $results->fetch(PDO::FETCH_ASSOC)) {
        $product["sizes"][] = $row["size"];
    }

We're using fetch which retreive single data at a time so we're using while loop here for fetching all records one by one and store in an array called $product['sizes'] and return complete array when all records are fetched by while loop.

1 Answer

Thank you very much.