2.6 KiB
isChild, title, anchor
isChild | title | anchor |
---|---|---|
true | Interacting with Databases | databases_interacting |
Interacting with Databases
When developers first start to learn PHP, they often end up mixing their database interaction up with their presentation logic, using code that might look like this:
{% highlight php %}
-
<?php
foreach ($db->query('SELECT * FROM table') as $row) {
echo "
- ".$row['field1']." - ".$row['field1']." "; } ?>
This is bad practice for all sorts of reasons, mainly that it's hard to debug, hard to test, hard to read and it is going to output a lot of fields if you don't put a limit on there.
While there are many other solutions to doing this - depending on if you prefer OOP or functional programming - there must be some element of separation.
Consider the most basic step:
{% highlight php %}
<?php function getAllFoos($db) { return $db->query('SELECT * FROM table'); } $results = getAllFoos($db); foreach ($results as $row) { echo "<li><?= $row['field1'] ?> - <?= $row['field1'] ?></li>
<?php endforeach ?>
{% endhighlight %}
This is essentially the same as what most modern frameworks are doing, albeit a little more manual. You might not need to do all of that every time, but mixing together too much presentation logic and database interaction can be a real problem if you ever want to unit-test your application.