HTML and CSS Reference
In-Depth Information
Separating Presentation and Logic
The point here is that it's common to mix PHP and HTML in this way. You create your
loop using PHP but you define the HTML in the page rather than in echo() calls
inside your PHP code. This is generally considered the best practice for PHP. You
should write as much HTML as possible outside your PHP scripts, using PHP only
where it's necessary to add bits of logic to the page. Then you can keep the bulk of
your PHP code at the top or bottom of your page or in included files to separate the
presentation of your data and the business logic implemented in code. That makes
your code easier to work on in the future. As an example, rather than sprinkling the
validation code throughout my page, I put it in one function so that a programmer
can work on it without worrying about the page layout. By the same token, I could
have built the unordered list inside the validation function and just returned that, but
then my HTML would be mixed in with my PHP. Cleanly separating them is generally
the best approach.
After I've listed the errors, I can go ahead and present the form fields. Before I do that,
let me show you one more thing I've added to the page. I included a style sheet that
defines one rule: label.error . The labels for any fields with errors will be assigned to
this class so that they can be highlighted when the form is presented. Here's the style
<style type=”text/css”>
label.error {
color: red;
Okay, now that everything is set up, let's look at how the name field is presented. Here's
the code:
<?php if (array_key_exists('name', $errors)) { ?>
<label for=”name” class=”error”><b> Name: </b></label>
<?php } else { ?>
<label for=”name”><b> Name: </b></label>
<?php } ?>
<br />
<input name=”name” value=”<?= strip_tags($_POST['name']) ?>” /></p>
This code is a lot different from the old code I used to present the name field in the origi-
nal listing in this example. First, I include an if statement that checks to see whether
Search WWH ::

Custom Search