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.
Check post fields are having values or not like below:
Simply add a condition that checks if the variable isn't empty. If so, print the required line.
Note: Consider validating/escaping the input data prior to printing them.
Update - In case of multiple fields:
Just try:
This uses a
?:
ternary operator to determine if the$_POST["phone"]
is empty or not. Also use<?=
shorthand for<?php echo
whenecho
ing inside html tags.Warning
Also, beware of XSS use
htmlentities()
to escape the output likehtmlentities($_POST["phone"])
also, use more specific validation for filteringphone
andemail
strings.