I did my reading on about using the ternary operator for setting initial default value for undefined variables. So thats what i tried to do at the top of my scripts as you will see.
Yet i still get the undefined variable errors on my contact form's input value's fields.
Can anyone explain why?
My code:
<?php
if (isset($_POST["submit"])) {
$user_name = isset($_POST["name"]) ? $_POST["name"] : "";
$user_email = isset($_POST["email"]) ? $_POST["email"] : "";
$user_age = isset($_POST["age"]) ? $_POST["age"] : "";
$validation_errors = "";
$error_counter = null;
if (empty($_POST["name"])) {
$validation_errors .= "<li class='validation_errors'>Please input your name.</li>";
$error_counter++;
}
if (empty($user_email)) {
$validation_errors .= "<li class='validation_errors'>Please input your email.</li>";
$error_counter++;
}
if (empty($user_age)) {
$validation_errors .= "<li class='validation_errors'>Please input your age.</li>";
$error_counter++;
} elseif (intval($user_age) < 18) {
$validation_errors .= "<li class='validation_errors'>You must be over 18 years old.</li>";
$error_counter++;
}
if ($error_counter != 0) {
// $validation_errors = "<li class='validation_success'>Message successfully sent!</li>";
$error_design = "<hr> <p id='error_msg'>Please Fix Below Errors: <p>";
};
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SandBox</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" href="css/animate.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<header>
</header>
<form action="" method="post">
<div class="input_group">
<label for="name">Name</label>
<input type="text" name="name" value="<?php echo htmlspecialchars($user_name); ?>">
</div>
<div class="input_group">
<label for="email">eMail</label>
<input type="email" name="email" value="<?php echo htmlspecialchars($user_email); ?>">
</div>
<div class="input_group">
<label for="age">Age</label>
<input type="text" name="age" value="<?php echo htmlspecialchars($user_age); ?>">
</div>
<input type="submit" value="Send" name="submit" id="submit">
<?php echo $error_design; ?>
<div>
<ul>
<?php echo $validation_errors; ?>
</ul>
</div>
</form>
<footer></footer>
</body>
</html>