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

Development Tools Using PHP with MySQL Filtering Input for Queries Using a WHERE Clause

Storing results to a variable

At the end of the function, Randy stores the results to a variable called $product, and then returns that variable, like this:

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

Wouldn't it be simpler to just return the results directly, without storing to a variable:

return $results->fetch(PDO::FETCH_ASSOC);

Is there any reason not to do this?

1 Answer

Erik McClintock
Erik McClintock
45,783 Points

Evan,

Though there may even be other reasons, one simple reason to store your results to a variable before returning them is that it allows for easier reuse and maintenance of your code. Consider that you might want to use what is returned by $results->fetch(PDO::FETCH_ASSOC); in more places than one: it would be much simpler to call $product over and over again rather than $results->fetch(PDO::FETCH_ASSOC); time and time again. Additionally, if you ever wanted to slightly tweak what you were accessing via $results->fetch(PDO::FETCH_ASSOC);, rather than having to go through and change every instance of $results->fetch(PDO::FETCH_ASSOC); that you have throughout your code, you would only need to edit it once: where you assigned it to your $product variable. It's the DRY principle: Don't Repeat Yourself. You also get a bonus from assigning it to a variable because you can name your variable something that makes sense for the data: reading $product makes a little more sense as to what you're getting somewhere over $results->fetch(PDO::FETCH_ASSOC);. That isn't very descriptive, but $product (or whatever else you choose to name your variable(s)) can be.

As I say, there may be other good reasons that are shared here, but even just at a basic level, to keep your code reusable and maintainable is one reason that you would store the results in a variable before returning them.

Erik