简体   繁体   中英

PHP setting input values with isset

I was wondering if there is a shorter way of writing the following code:

<input type="text" name="username" value="<?if(isset($_POST['username'])){ echo $_POST['username']; }?>" />

I hate having to do this will all my forms as the isset() check really messes up my HTML and scares away the frontenders.

you can make a helper:

function req($key, $default = '')
{
  return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}

<input name="user" value="<?php echo htmlentities(req('user')) ?>" />

@marvin's suggestion is nice for your script as well

regarding the front-end folks, i would say give them some basic php to use, like in this php for designers tutorial: http://www.digital-web.com/articles/php_for_designers/

learning the basic scrips i think is better than using an external templating system

You can assign the values in php part and then just echo in html

$username = isset($_POST['username'])?$_POST['username']:'';

<input type="text" name="username" value="<?php echo $username;?>" />

Why not just

<input type="text" name="username" value="<? echo $_POST['username']; ?>" />

if $_POST['username'] is empty then it will cause a value of "" anyway.

I feel like I am missing something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM