How can I not include a line in the action page if

2019-08-26 02:36发布

Suppose I have the following form, where the input field Phone is optional.

<form action="welcome.php" method="post">
   Name: <input type="text" name="name"><br>
   Phone (optional): <input type="text" name="phone"><br>
   E-mail: <input type="text" name="email"><br>
   <input type="submit">
</form>

I want to display the submitted data in the action page. So here it is the welcome.php page:

<html>
   <body>
      Welcome <?php echo $_POST["name"]; ?><br>
      Your phone number is: <?php echo $_POST["phone"]; ?>
      Your email address is: <?php echo $_POST["email"]; ?>
   </body>
</html>

My question is how can I exclude the Your phone number is: <?php echo $_POST["phone"]; ?> section if the user doesn't input any value for the Phone in the form? Simply saying, if user leaves a field empty, the corresponding sentence will not be generated in the action page.

What would be the best possible way to achieve that?

I'm just trying to learn the different approaches of form handling. I'll appreciate any suggestion. Thanks in advance.

标签: php forms
3条回答
【Aperson】
2楼-- · 2019-08-26 03:06

Check post fields are having values or not like below:

<html>
   <body>
    <?php if(!empty($_POST['name'])) echo 'Welcome '. $_POST['name'] ?><br>
    <?php if(!empty($_POST["phone"])) echo 'Your phone number is: '. $_POST["phone"]; ?>
    <?php if(!empty($_POST["email"])) echo 'Your email address is: '. $_POST["email"]; ?>
   </body>
</html>
查看更多
乱世女痞
3楼-- · 2019-08-26 03:08

Simply add a condition that checks if the variable isn't empty. If so, print the required line.

<?php if(!empty($_POST['phone'])) {   
      echo 'Your phone number is: '. $_POST["phone"] . '<br />';
}
?>

Note: Consider validating/escaping the input data prior to printing them.

Update - In case of multiple fields:

$fields = array(
'phone' => 'This is my phone number',
'address' => 'I live at',
'zipcode' => 'And my zip code is:'
);

foreach($fields as $fieldname => $label){
  $value = $_POST[$fieldname]; //consider escaping/validating the value...
  if(!empty($value)){
     echo $label . ' ' . $value . '<Br />';
  }
}
查看更多
乱世女痞
4楼-- · 2019-08-26 03:23

Just try:

<html>
   <body>
      Welcome <?= $_POST["name"]; ?><br>
       <?= (!empty($_POST["phone"])) ? 'Your phone number is: ' . $_POST["phone"] : ''; ?>
      Your email address is: <?= $_POST["email"]; ?>
   </body>
</html>

This uses a ?: ternary operator to determine if the $_POST["phone"] is empty or not. Also use <?= shorthand for <?php echo when echoing inside html tags.

Warning

Also, beware of XSS use htmlentities() to escape the output like htmlentities($_POST["phone"]) also, use more specific validation for filtering phone and email strings.

查看更多
登录 后发表回答