I was trying to make a POST request form in PHP. When the user submits the form, the codes should validate the inputs and put it into an array called errors. After that, the system checks if that array is empty or not. If it has something, it will bump an alert box.
The problem I am facing is no matter how I try to assign the values, the error array still empty. Below is the full codes.
<?php
$errors = array('name' => '', 'age' => '' ); // array containing errors
// check get request. The GET will be an array storing data to be transfered to server as GET.
// _ is global var. GET belows will take the value when the submit button pressed
if(isset($_POST['submit'])){ // when user submit POST request
errCheck();
if(!empty($errors['name'])) {
phpAlert($errors['name']);
}; // check if errors exist
if(!empty($errors['age'])) {
phpAlert($errors['age']);
};
}
function errCheck() { // validate user input
if(empty($_POST['name'])) {
$errors['name'] = 'Name can\'t be emty';
}
elseif(!preg_match('/^[a-zA-Z\s]+$/', $_POST['name'])){
$errors['name'] = 'Only letters available for name.';
};
if(empty($_POST['age'])) {
$errors['age'] = 'Age can\'t be empty';
}
}
function phpAlert($msg){ // in case errors exist
echo $msg;
echo '<script type="text/javascript">alert("' . $msg . '")</script>';
};
?>
<!DOCTYPE html>
<html>
<head>
<title> my PHP </title>
</head>
<body>
<h4 class="center">Add a Person</h4>
<form class="white" action="15.php" method="POST"> <!-- GET request form -->
<label>Name: </label>
<input type="text" name="name"> <!-- name is the key for http request -->
<label>Age: </label>
<input type="number" name="age">
<div class="center">
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
Expect result: alert box appears when user doesn't type anything or write something not letters in 'name' input.
Current problem: the codes run but it always bump 2 blank alert boxes no matter what I type in inputs. Errors array always blank.
What I have tried (but not work): making errors global array, rearrange the codes, print_r everything ($_POST has values but not $errors), remake function phpAlert.
Editted: made the codes easier to be read.
$errorsarray to the function and then return it again.if ($x == $y) { echo $x; }since it makes it much harder to read. There's no bonus points for writing compact code but there is for readable code.