How do I separate logic from presentation?
Separate it.
Although it is called business logic from presentation logic . You have logic in both layers. The name says it all:
- first follow your "logic"
- then go to "presentation".
Taking your example, it should be something like this
$res = $stmt->get_result(); $data = array(); while ($row = mysqli_fetch_assoc($res)) { $data[] = $row; }
although I would use a more intelligent approach to retrieve data from a database, something like this:
$data = $db->getArr("SELECT ...");
then repeat all steps for all interactions with the database or other services. Your goal is to have all the data ready for business logic. Then your business logic is over, and you can refer to the presentation.
You can tell the good separation from the bad , if you can easily exchange template engines (you cannot do this using an approach from another answer, mind you) - so the particular engine isnβt. "Let's take the simplest option - PHP
Create a file called tpl.php
and put this code there
<table> <?php foreach ($data as $row): extract($row); ?> <tr> <td><?=$title</td> and so on </tr> <?php endforeach ?>
then include this file in the business logic file. Or - better - in a higher-level template.
You can see a good example of life in this section.
Using this separation, you can:
- Use a powerful editor that can do syntax highlighting and hint (although I doubt you are using it).
- Pass on your design to a professional designer.
- Easily change presentation technology from HTML to AJAX.
- use the same engine for different sites with different forms.
- The introduction of any number of "themes" or "skins".
- Stay alive by adding some rich decoration from HTML, CSS or JS.
Although all this is simply not possible with your current approach or approach from another answer. The idea is to separate questions.
source share