PHP check empty post data in array - php

HTML markup
<input name="one[name]">
<input name="one[email]">
<input name="two[message]">
...
alot input
..
I pass that two array data from jquery to php, i need check if the field is empty by php and exit when find one of them is empty.
But i dont want do it one by one, can it done by php function like foreach or other?
This is what i tried but fail.
$data_one = $_POST['one'];
$data_two = $_POST['two'];
if (empty( $_POST['one'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}
Above code keep return field are filled message, whether i fill the input field or not.
Thanks so much.

$allFilled = true;
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
$allFilled = false;
exit('some fields are empty');
}
}
if($allFilled){
exit('all fields are filled');
}

Making use of array_filter and count functions
<?php
$data_one = $_POST['one'];
$data_one_filter = array_filter($_POST['one']); //Remove indexes of null or 0 - certainly name and email can't be 0
$data_one_count = count($_POST['one']); //count actual number of POST variables
$data_two = $_POST['two'];
if (count($data_one_filter) === $data_one_count) {
exit('fields are filled');
} else {
echo('some fields are empty');
// continue other function
}

You are sending data as array. So you seed to check this data as array like this:
$data_one = $_POST['one']['name'];
$data_two = $_POST['two']['message'];
if (empty( $_POST['one']['name'] )) { // i only need check `$data_one` in this example
exit('some field are empty');
} else {
echo('field are filled');
// continue other function
}

Try this
foreach($_POST['one'] as $key=>$value){
if(empty($value)){
exit('some field are empty');
}
}
echo "All fields are filled";

Related

Return not working on empty check function PHP

Thank you for help. Anyway, i'm a student and i'm stuck making a function that does a simple empty() check on a key in a array. If it is empty() -> it will fill in the error and print it on a div element.
This is my code:
function validateData($data, $formErrors) {
if (empty($data)) {
$formErrors = 'name is required.';
}
echo $formErrors;
}
Executing the function:
$data = $_POST;
$formErrors = [];
// Elementen valideren
validateData($data['name'], $formErrors['name'] = '');
This is the thing that i want to achieve:
if (empty($data['surname'])) {
$formErrors['surname'] = 'Surname is required.';
}
Looks like it is not returning the value of that key or whatelse?
Thanks alot!
You need to make it a reference parameter with & if you want to assign it in the function.
function validateData($data, &$formErrors) {
if (empty($data)) {
$formErrors = 'name is required.';
}
echo $formErrors;
}
And you can't use an expression when passing a reference parameter, it has to be just the variable. It should be:
$formErrors = ['name' => ''];
validateData($data['name'], $formErrors['name']);

How to handle empty post (upto 20 post) without using empty() and "&&" operator

I am receiving post values. I want a suggestion for logic to handle empty or not set post values.
Is there such a way if one of them receives empty post, the $Data array should not receive anymore values and make it empty. In other words, i am trying to immitate the try and catch feature. If on any POST is empty, ignore reading the rest of POST and make that array as empty
Is my second draft considred valid?
First draft
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWSCHEDULE_SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWSCHEDULE_SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}
if(empty($DATA)){
//do something
}else{
//do something else
}
Second draft
try{
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTITLE');
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTYPE');
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
unset($DATA);
}
You can use one if statement with all required POST parameters.
if(!empty($_POST['var1']) && !empty($_POST['var2']) && !empty($_POST['var3']) && !empty($_POST['var4'])):
/*and then assign all the POST values to a $DATA array as you want.*/
$DATA['var1'] = $_POST['var1'];
$DATA['var2'] = $_POST['var2'];/* and so on..*/
endif;
I personally prefer to white list values that I loop through and assign.
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
$at_least_one_empty = false;
foreach($valid_keys as $data_key)
{
$data[$data_key] = isset($_POST[$data_key])
? trim($_POST[$data_key]) // Remove accidental user whitespace.
: ''; // If unsubmitted - set to empty string.
if($data[$data_key] === '')
$at_least_one_empty = true;
}
if($at_least_one_empty) {
unset($data);
} else {
process($data);
}
Note with the sample code above an unsubmitted value will be assigned the empty string. This might not be the behaviour you want.
However if you just want to assign and check you received all inputs this might do (no filtering or validation):
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
foreach($valid_keys as $data_key)
$data[$data_key] = $_POST[$data_key] ?? null;
$not_all_received = in_array(null, $data, true);

If any field in array is not empty, display message - PHP / [POST] form

I have a form with 25+ fields. I want to display a message if ANY of the fields in the array are NOT empty.
$customfields = array('q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10', 'q11', 'q12', 'q13', 'q14', 'q15', 'q16', 'q17', 'q18', 'q19', 'q20', 'q21', 'q22', 'q23', 'q24');
I've taken a look at similar SO questions for verifying that all fields are not empty, i.e.:
$error = false;
foreach($customfields as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "Here's an awesome message!";
} else {
echo "None for you, Glen Coco.";
}
How do I do the opposite - display a message if ANY one or more than one fields in the array are not empty?
Thanks in advance!
I think you want to take a look into the NOT operator.
You can just write this:
if (!empty($_POST[$field])) {
//^ See here the NOT operator
$error = true;
}
For more information see the manual: http://php.net/manual/en/language.operators.logical.php
Do the opposite comparison in the if:
$error = false;
foreach($customfields as $field) {
if (!empty($_POST[$field])) {
$error = true;
break; // get out of foreach loop
}
}

Display error if empty field - PHP

I want to display an error on the same page if any field is empty.
I've got this, which works but the empty error is displayed as soon as the page is loaded instead of appearing once empty fields are submitted.
<?php
// Required field names
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$error = true;
}
}
if ($error)
{
echo "ALL FIELDS ARE REQUIRED";
}
else
{
echo header('Location: formSuccess.php');
}
?>
Any ideas? -- UPDATE // IVE TRIED ALL ANSWERS, nothing has worked so far
Wrap everything you check on post in this:
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
// Your code containing checks here
}
This way, it will only trigger when a POST request is used.
If you have an input you know will always be submitted with the form, such as a hidden one:
<input type='hidden' name='formsubmit' value='1'>
Then you can test for this before validating the other inputs
if($_POST["formsubmit"]) {
// Required field names
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "ALL FIELDS ARE REQUIRED";
} else {
header('Location: formSuccess.php');
}
}
Also you don't echo the return of header()
OR another way ( I have something similar in one of my pages)
function check_presence($value){
return isset($value) && $value!=="";
}
function validate($required){
global $error
foreach($required as $field){
$value = trim($_POST[$field]);
if (!check_presence($value)){
$error = true;
}
}
return $error;
}
then on the page containing the form and its validation code
$required = array('triangleSide1', 'triangleSide2', 'triangleSide3');
if(isset($_POST["submit"]){
$error = validate($required);
if ($error){
echo "ALL FIELDS ARE REQUIRED";
}
}
Try isset instest of empty!!!
if (empty($_POST[$field]))
Become
if (isset($_POST[$field]))

Check if atleast one field is not empty in PHP

I have these fields: weight, size_1, size_2, size_3
How can I check so minimum one of these fields are filled.
If its under the minimum then it should output "Error, fill one atleast"
I can do this with long if statements, that checks for empty, but is their a better way?
The fields come from an form submission, so it looks like this to get them:
$_POST['weight'];
$_POST['size_1'];
$_POST['size_2'];
$_POST['size_3'];
Assuming they are all in an array:
function check_for_input($array){
foreach($array as $value){
if($value != "") return true;
}
return false;
}
Use it like so:
if(check_for_input($_POST)){ /*...*/ }
else { die("Error, fill one at least"); }
Update with filter:
Assuming they are all in an array:
function check_for_input($array, $filter){
foreach($array as $key=>$value){
if($value != "" && in_array($key, $filter)){
return true;
}
}
return false;
}
Use it like so:
$filter = array('weight', 'size_1', 'size_2', 'size_3', /*...*/);
if(check_for_input($_POST, $filter)){ /*...*/ }
else { die("Error, fill one at least"); }

Categories