Check whether $_POST-value is empty
Solution 1:
isset()
will return true if the variable has been initialised. If you have a form field with its name
value set to userName
, when that form is submitted the value will always be "set", although there may not be any data in it.
Instead, trim()
the string and test its length
if("" == trim($_POST['userName'])){
$username = 'Anonymous';
}
Solution 2:
If the form was successfully submitted, $_POST['userName']
should always be set, though it may contain an empty string, which is different from not being set at all. Instead check if it is empty()
if (isset($_POST['submit'])) {
if (empty($_POST['userName'])) {
$username = 'Anonymous';
} else {
$username = $_POST['userName'];
}
}