开发者

Checking view for PHP variables

开发者 https://www.devze.com 2023-03-04 17:55 出处:网络
This is how I\'ve been checking to see if variables are set when returned to my view. <div> <label for=\"username\">Username</label>

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

0

精彩评论

暂无评论...
验证码 换一张
取 消