This is how I've been checking to see if variables are set when returned to my view.
<div>
<label for="username">Username</label>
<input type="text" name="usernam开发者_Python百科e" id="username" <?php if(isset($_POST['username'])) { echo "value=\"". $_POST['username'] . "\""; } ?> />
<?php if(isset($username_error)) { echo "<label>" . $username_error . "</label>"; } ?>
</div>
I feel like there could be a better approach, or even a shorter way to check and echo out these values?
When I deal with form submissions or possibly not initialized variables in PHP I do this:
$username = isset($_POST['username']) ? $_POST['username'] : '';
$username_error = usernameValid($username) ? true : false;
Then just echo out the username and do a quick if($username_error) to determine if you need to display the error. It's probably best to store if a submitted form field is valid or not and the error message separately.
You could build the HTML independently, loading your template with DOMDocument.loadHTML and adding the attributes conditionally (JavaScript-like) via the DOM. That has the advantage of highlighting your HTML structure without as many inline checks.
I'd suggest using a library or framework that does the hard work for you.
See:
A PHP and jQuery form creation and validation library available?
HTML Form Library for PHP 5
精彩评论