I’m trying to figure out how i can fix this becasue the post parameters of the form are: answer1[2], and answer2[4]. The number inside the brackets represent the id of the question it belongs to. Reason I need to know how to do this is because its not returning an error for the answers when its an empty form submission.
if((empty($_POST['answer1'])) || (trim($_POST['answer1'])=="") || ($_POST['answer1'] == NULL) || (!isset($_POST['answer1']))){$errors = "yes";}
if((empty($_POST['answer2'])) || (trim($_POST['answer2'])=="") || ($_POST['answer2'] == NULL) || (!isset($_POST['answer2']))){$errors = "yes";}
// Error checking, make sure all form fields have input
if ($errors == "yes") {
// Not all fields were entered error
$message = "You must enter values to all of the form fields!";
$output = array('errorsExist' => true, 'message' => $message);
}
You wrote that you have problems to understand what is going on. So let’s check one of the if-clauses in depth:
This can be much simpler written as:
That’s because
NULLvalues areempty()and!isset(...)values are empty as well. You had already checked that in the first, so no need to check it again.Then there is no need to add brackets around everything. Add them only when actual needed, to make your code easier to read.
Let’s change the code based on that:
Next part is the
$errorsvariable. There is no need to make it say yes and no, while your meantrueorfalse. Next to that, the variable should be initialized for the case that everything went through ok. Let’s change the code a bit more:So now the code looks a bit better to find your actual error. To find the error, you need to inspect which values are actually submitted to your form:
Request the page again and you will see which data you have submitted so you can check whether or not you error-check the right fields.
Another method is to expect that all submissions have errors. So the default would be
true. Then only if all fields do validate,$errorsis set tofalse.So in your case, if you do not do the right error-checking your response will always return no errors, even the form in practice has. That’s why you should control if your error checks are actually working.
According to your feedback in comment, it’s clear that you need to reference the item inside the
answer1andanswer2post field. You just have checked the wrong field.So just replace
$_POST['answer1']with$_POST['answer1'][2]and the same for the other answer. This is the example if clause foranswer1:Just always test the right variables and it should work like expected.
Related: How do I create a server-side form submission script that has client-side characteristics?