简体   繁体   中英

Dealing with missing data on HTML form using PHP

I am creating a HTML for that has a lot of input fields that are optional. The PHP server scripts takes the data put in by the user and essentially forms a sentence.

Hello my name is <?php echo $_POST["name"]; ?> and I am <?php echo $_POST["age"]; ?>

Right now if the user submits the form entering name and age there is no problem. However if you omit one or both of the inputs, the PHP output has an error message embedded in the sentence. I would like it to handle all omissions by simply leaving the area blank.

Example:

Name: Ben
Age: (blank)

Hello my name is Ben and I am.

Can this be achieved? Also, is there a way to write an if/else statement that if any value is entered by the user do this?

Thanks!

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

echo 'Hello, my name is ' . $name . ', and I am ' . $age . ' years old.';

Hi you should use isset() like says Julian H you may use it in conditions to make different sentences if age is set or not

isset() returns TRUE or FALSE

i made this for you (with _GET but you can use _POST, it was more easy to test

<?php

$html = 'Hi, ';

if(isset($_GET['name']) AND $_GET['name'] != '')
{
    $html .= 'my name is '.strip_tags($_GET['name']).' ';
}

if(isset($_GET['name']) AND $_GET['name'] != '' AND isset($_GET['age']) AND $_GET['age'] != ''  )
{
    $html .= 'and ';
}

if(isset($_GET['age']) AND $_GET['age'] != '' )
{
    $html .= 'i am '.strip_tags($_GET['age']).' years old ';
}

echo $html;

and very important : i use strip_tags() to remove html tags, and avoid XXS attacks

so finally i can get these sentences :

Hi, my name is Acuao

Hi, my name is Acuao and i am 23 years old

Hi, i am 23 years old

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