0

So curiosity got to me. I always try to avoid creating variables that will only be used once, instead I try to use it directly (unless it's a lot of text, for example MySQL queries).

What I usually do is something like this:

$getSomethingSql = 'LONG SQL';
$getSomething = $dbConnection->prepare($getSomethingSql); // or query if no parameters are needed
// Some binds etc if needed
$getSomething->execute(); // if prepared statements are used
$something = $getSomething->fetchAll(PDO::FETCH_ASSOC);

foreach ($something as $s) {}

Now, the $getSomethingSql is only used once but is stored as a variable since it can be a long string and thus this looks better. However, I was curious if there is any advantage of using above versus the code below:

$getSomethingSql = 'LONG SQL';
$getSomething = $dbConnection->prepare($getSomethingSql); // or query if no parameters are needed
// Some binds etc if needed
$getSomething->execute(); // if prepared statements are used

foreach ($getSomething->fetchAll(PDO::FETCH_ASSOC) as $s) {}

Does these 2 codes do the same? And is there a (huge) performance difference, or is one of them cleaner?

Joshua Bakker
  • 2,288
  • 3
  • 30
  • 63
  • Better may be to use your own class or wrapper function - pass it a SQL query and some parameters, have it run the PDO prepared statement, and use the `fetchAll()` to return back the record set as an array, which can then be used in your code. This way, you aren't re-writing your DB connections, error checking, etc. and when updates happen you have one place to update – ivanivan Nov 29 '18 at 15:33
  • Well, the code I'm working in isn't mine and it actually always includes a "config" file containing the database connection. Even then, it could be done both ways I describe above, meaning I'd still wonder the same. – Joshua Bakker Nov 29 '18 at 15:36

1 Answers1

1

Internally they'll do the same thing. The only difference is that in one case it will use your explicitly created variable to hold the results of fetchAll() and in the second case it will make use of a temporary variable.

pmmaga
  • 410
  • 7
  • 18