You’re right, faster and easier, because separating logics is not at all about that. It’s about improving your code and design. The coder is happy because he doesn’t have to deal with HTML code, it’s not his job afterall. The designer is happy because he doesn’t have to deal with PHP code, business logic. You can’t seriously ask designers to fetch data from a database using “mysql_fetch_array”-like functions nor to “encrypt” their beautiful HTML codes into “echos”. It’s not a life for a designer, I think it would even kill “it”.
So let’s clean up your code to see how designer-friendly it could be :
- Replace the while loop by a good old foreach. That can be achieved by using Data Access Objects that implement the PHP 5 Iterator interface.
- Avoid if and long conditions. They can be replaced by ternary operators for example.
- Don’t “encrypt” plain HTML code in a echo call. You have to escape quotes and concatenate PHP variables… Why suffer when you can use the short tags <?= ?> ? From the Introduction chapter of the manual we can read that PHP is a « scripting language that is especially suited for Web development and [b]can be embedded into HTML[/b] ». That’s why so many people claim that PHP itself can be used as a template engine, because it’s meant for that ! In some way I think Smarty-like templates and many tutorials published on the Web lead developers in the wrong direction. I also strongly recommand you to read the [url=http://www.php.net/manual/en/language.basic-syntax.php]Basic syntax chapter. I think most developers just forget about how simple things should be, because PHP is all about making us happy…ly ever after.
- Avoid copying and pasting your code at all cost. Make your code reusable. Use functions, group them into classes as methods… The strings that your echo output are pretty much the same, making the if useless.
Here’s your code rewritten following these principles :
<select name="category">
<option value="0">bitte auswählen</option>
<?php foreach ($categories as $row) : ?>
<option value="<?= $row['catid'] ?>"<?= ($category == $row['catid']) ? ' selected' : '' ?>><?= $row['title'] ?></option>
<?php endforeach; ?>
</select>