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.
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 />';
}
}
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 echo
ing 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.
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>