Form processing $_POST to variables automatically - php

I have about 40 items in my FORM and i'm trying to give all the Name= properties a variable for process without having to write each out manually. am I missing something here, cause the code below is not working. (name="comp1", name="comp2"... $comp1, $comp2)
$en = array_merge($em, $_POST);
$valid = true;
foreach($_POST as $value) {
if(!isset($value)) {
$valid = false;
}
}

If something is not in $_POST, the foreach will not loop through it. Isset() will always return true, because the foreach loops through all values in $_POST.

foreach($_POST as $k=>$val) {
//$$k = $val;
if(!isset($$k)){
echo "==NO==";
}
}

the POST will always be set, unless you disable the field with something like this:
<input disabled="disabled"/>
If the filds doesn't have this attribute, the only way to check if the field was filled is a comparse with an empty string, with $value == '' this way:
foreach($_POST as $key => $value) {
if($value == '') {
$valid[$key] = false;
}else{
$valid[$key] = true;
}
}
You will have now an array ($valid) that will look like:
var_dump($valid['field1']); //prints true, the field was filled
var_dump($valid['field2']); //prints false, the field was NOT filled

Related

Shortcut for checking if all $_POST fields are filled in php

I know that I can check if the superglobal $_POST is empty or not by using
empty / isset
However, I have many fields here. Is there any shortcut to check if all fields are filled? Instead of doing
if (!empty($_POST['a']) || !empty($_POST['b']) || !empty($_POST['c']) || !empty($_POST['d']).... ad nauseum)
Thanks in advance!
You can use array_filter and compare both counts
if(count(array_filter($_POST))!=count($_POST)){
echo "Something is empty";
}
You can loop through the $_POST variable.
For example:
$messages=array();
foreach($_POST as $key => $value){
if(empty($value))
$messages[] = "Hey you forgot to fill this field: $key";
}
print_r($messages);
Here's a function I just authored that might help.
if any of the arguments you pass is empty, it returns false. if not it'll return true.
function multi_empty() {
foreach(func_get_args() as $value) {
if (!isset($value) || empty($value)) return false;
}
return true;
}
Example
multi_empty("hello","world",1234); //Returns true
multi_empty("hello","world",'',1234); //Returns false
multi_empty("hello","world",1234,$notset,"test","any amount of arguments"); //Returns false
You can use a foreach() loop to check each $_POST value:
foreach ($_POST as $val) {
if(empty($val)) echo 'You have not filled up all the inputs';
}

How do I suppress this foreach warning when the function that contains it relies on $_POST data

I have the following code which functions as intended when $_POST values are set, however, if no $_POST values(IE when the page is first loaded) are set I get "Warning: Invalid argument supplied for foreach() in..." $_POST is always going to be empty until the user clicks submit. I have tried empty(), isset() and now count().
if(isset($_POST['submitbtn'])){
$errors = CheckFormErrors();
if(count($errors) == 0){
$data = CleanFormData();
print_r($data);
}
}
Here is the function being called(not yet complete, but it is working):
function CleanFormData(){
foreach($_POST as $key => $value){
if($key == 'description'){ continue; }
if($key == 'file'){ continue; }
if($key == 'role'){ continue; }
$_POST[$key] = is_array($key) ? $_POST[$key]: strip_tags($_POST[$key]);
}
return $_POST;
}
I thought that I could surpress the error by putting it in a conditional statement, evidently that is incorrect. A little help?
As already stated in comments, you have to check if the superglobal $_POST is empty before calling the foreach itself (inside the function), not outside the function - this way you don't have to check for !empty($_POST) every time you are calling this function.
function CleanFormData() {
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
// Loops here
}
}
return $_POST;
}

How can I get $_GET values to a variable

In my page, there are multiple $_GET values. ie
if(isset($_GET["projects"]))
{ ..... }
else if(isset($_GET["research"]))
{ ...... }
else if(isset($_GET["publication"]))
{ ..... }
...upto 10 elseif's
Can I shorten this?
Can I get these values {projects,research, publication,..} in a variable.?
Ok so I guess I figured out what you want from your comments. Lets see.
$types = array('projects', 'research', 'publication'); // add as many as you want
$valid = array_intersect_key($_GET, array_flip($types));
if (count($valid) > 1)
die "More than one category is set, this is invalid.";
if (!$valid)
die "No category was set, you must choose one.";
foreach ($valid as $type => $value) // just to split this one element array key/value into distinct variables
{
$value = mysql_real_escape_string($value); // assuming you are using mysql_*
$sql = "SELECT * FROM table WHERE $type = '$value'";
}
...
Yes, you can assign these in a variable -
if(isset($_GET["projects"]))
{
$value = $_GET['projects'];
}
else if(isset($_GET["research"]))
{
$value = $_GET['research'];
}
else if(isset($_GET["publication"]))
{
$value = $_GET['publication'];
}
echo $value;
I'm guessing you're expecting a single value in $_GET, like ?projects=foo or ?research=bar. In that case:
$type = key($_GET);
$value = $_GET[$type];
echo "$type = $value";
$projects = $_GET["projects"];
Or just use directly from $_GET, this is an associative array with all the values.
foreach ($_GET as $key => $value){
if(!empty($value)){
$type = $key; //if you expect a single item
$type[] = $key; //if you expect multiple items
}
}
if the intent is to check if values on a form have been answered/filled out you could use
if(isset($_GET['project'] || ... || isset($_GET['publication'])
{
// Insert Code Here
}
else
{
// Insert Code Here
}
The above code is assuming the fields are not text fields or textareas if those are the types of inputs then instead of
if(isset($_GET['project']))
use
if($_GET['project'] != "")
I didn't completely understood what you are saying but looks like that you are trying to execute something when all $_GET is true. If so then use the code below
if(isset($_GET["projects"]) && isset($_GET["research"]) && isset($_GET["publication"]) )
{ ..... }
Hope this helps you

how to check multiple $_POST variable for existence using isset()?

I need to check if $_POST variables exist using single statement isset.
if (isset$_POST['name'] && isset$_POST['number'] && isset$_POST['address'] && etc ....)
is there any easy way to achieve this?
Use simple way with array_diff and array_keys
$check_array = array('key1', 'key2', 'key3');
if (!array_diff($check_array, array_keys($_POST)))
echo 'all exists';
$variables = array('name', 'number', 'address');
foreach($variables as $variable_name){
if(isset($_POST[$variable_name])){
echo 'Variable: '.$variable_name.' is set<br/>';
}else{
echo 'Variable: '.$variable_name.' is NOT set<br/>';
}
}
Or, Iterate through each $_POST key/pair
foreach($_POST as $key => $value){
if(isset($value)){
echo 'Variable: '.$key.' is set to '.$value.'<br/>';
}else{
echo 'Variable: '.$key.' is NOT set<br/>';
}
}
The last way is probably your easiest way - if any of your $_POST variables change you don't need to update an array with the new names.
Do you need the condition to be met if any of them are set or all?
foreach ($_POST as $var){
if (isset($var)) {
}
}
$variableToCheck = array('key1', 'key2', 'key3');
foreach($_POST AS $key => $value)
{
if( in_array($key, $variableToCheck))
{
if(isset($_POST[$key])){
// get value
}else{
// set validation error
}
}
}
That you are asking is exactly what is in isset page
isset($_POST['name']) && isset($_POST['number']) && isset($_POST['address'])
is the same as:
isset($_POST['name'], $_POST['number'], $_POST['address'])
If you are asking for a better or practical way to assert this considering that you already have all the required keys then you can use something like:
$requiredKeys = ['name', 'number', 'address'];
$notInPost = array_filter($requiredKeys, function ($key) {
return ! isset($_POST[$key]);
});
Remember, isset does not return the same result as array_key_exists
The following is a custom function that take an array for the required posted elements as a parameter and return true if they all posted and there is no any of them is empty string '' or false if there is at least one of them is not:
function checkPosts($posts){
if (!is_array($posts)) return "Error: Invalid argument, it should be an array";
foreach ($posts as $post){
if (!isset($_POST[$post]) || $_POST[$post] == '') return false;
}
return true;
}
// The structure of the argument array may be something like:
$myPosts = array('username', 'password', 'address', 'salary');
Use Array to collect data from form as follow:
PersonArray['name],
PersonArray['address],
PersonArray['email], etc.
and process your form on post as below:
if(isset($_POST['name'])){
...
}
Old post but always useful
foreach ($_POST as $key => $val){
$$key = isset($_POST[$key]) ? $_POST[$key] : '';
}
Use simple way with in_array and array_keys
$check_array = array('key1', 'key2', 'key3');
if(in_array(array_keys($_POST), $check_array)) {
echo 'all exists';
}
Note that the name of the submit button must be included in the array too.
if isset(($_POST['name']) && ($_POST['number']) && ($_POST['address']))
You can also use this. it might be more easy.

PHP local variable check

I am working with a set of variables that i check each time a page loads. I have successfully checked through $_REQUEST and $_SESSION, but am having trouble with the dynamci checking of variables assigned higher int he page, if they were set.
the following is my code:
$important_field = array('treatmentId','category','state','providerId','sellDoc','insuranceName','grossCharge','discount','allowable','patientPortion','insurancePortion','dateOfService','billFileLocation','eobFileLocation','fromTable');
foreach ($important_field as $key) {
if (!$$key || $$key == "none" || $$key == "" || $$key == NULL) {
if (!$_REQUEST[$key] || $_REQUEST[$key] == "" || $_REQUEST[$key] == NULL) {
if (!$_SESSION[$key]) {
// wow, guess it just wasn't set anywhere...
} else {
$user->sell->$key = $_SESSION[$key];
}
} else {
$user->sell->$key = $_REQUEST[$key]; $_SESSION[$key] = $_REQUEST[$key];
}
} else {
$user->sell->$$key = $$key; $_SESSION[$$key] = $$key;
}
}
Apparently evaluating $$key does not seem to do what i'm looking for as it never assigns the variable to the session... how should I be evaluating the $key to get the currently set value of say, field $eobFileLocation if it was already set in the PHP prior to the check?
Thanks,
Silver Tiger
Update:
ok, i have the following code, but there's still one bug with it. When i follow my process through af ew of these variables are set on each page and are carried over by the session variable as expected. The issue I am still having is that when i submit a new $_REQUEST variable which SHOULD change the session variable to the new submitted value, the script is finding a local variable ... where is it pulling $key and $$key from that is finding these as a local variable?
$important_field = array('treatmentId','category','state','city','providerId','sellDoc','insuranceName','grossCharge','discount','allowable','patientPortion','insurancePortion','dateOfService','billFileLocation','eobFileLocation','fromTable');
foreach ($important_field as $key) {
if (isset($$key) && !empty($$key) && $$key != "none") {
echo "Found local variable for ".$key.", i'll set the session and user to this.<br>\n";
$user->sell->$key = $$key;
$_SESSION[$key] = $$key;
} elseif (isset($_REQUEST[$key]) && !empty($_REQUEST[$key])) {
echo "Found submitted form variable for ".$key.", i'll set the session and user to this.<br>\n";
$user->sell->$key = $_REQUEST[$key];
$_SESSION[$key] = $_REQUEST[$key];
} elseif (isset($_SESSION[$key]) && !empty($_SESSION[$key])) {
echo "Found a session variable ".$key.", i'll set the user to this.<br>\n";
$user->sell->$key = $_SESSION[$key];
} else {
echo "There was no provided data for ".$key."<br>\n";
}
}
Any ideas why when i load the page it thinks the local (as listed above) is set? does $key and $$key read from $_SESSION['blah']/$_REQUEST['blah'] and think it's just $blah?
Are you sure this is what you want:
$user->sell->$$key = $$key;
should it not be
$user->sell->$key = $$key;
try using the empty function:
if (empty($$key) || $$key == "none")
if (empty($_REQUEST[$key]))
and the isset function:
if (!isset($_SESSION[$key]))
it is
$user->sell->$key = $$key;
not
$user->sell->$$key = $$key;
and
$_SESSION[$$key]
should be
$_SESSION[$key]
You're messing with your variables, this is not good. In fact, using two var signs ($$) describes a "variable variable".
$foo = "name";
$$foo = "value";
So you expect the following:
echo $foo; // => "name"
echo $$foo; // => "value"
What you maybe are not expecting, is:
echo $name; // => "value"
So you're better off cleaning up your code first.
Well, I have expressed my concerns about the cleanliness of this approach in the comments. Here's at least some more compact code without variable variables to do the same thing:
$keys = array('treatmentId', 'category', ...)
$values = array_filter(array_merge(
array_intersect_key($_SESSION, array_flip($keys)),
array_intersect_key($_REQUEST, array_flip($keys)),
compact($keys)
), function ($v) { return $v && $v != 'none'; });
$_SESSION = array_merge($_SESSION, $values);
foreach ($values as $key => $value) {
$user->sell->$key = $value;
}
// For debugging purposes:
//
// $diff = array_diff_key(array_flip($keys), $values);
// if ($diff) {
// 'No values for ' . join(', ', array_keys($diff));
// }

Categories