So I know how to error check an empty post value with an if empty combination, however how can this be done if the post data is an array and it needs to be applied to each value?
Example:
foreach (array($_POST['post_values']) as $test) {print_r($test); echo'<br />';};
where
<input name="post_values[value_1]">
<input name="post_values[value_2]"> etc.
I need to be able to say that if a value is not posted to any of the inputs, then that particular input = zero without applying a default value to the inputs themselves.
Therefore if value_1 = 5 and value_2 = blank, the array will show as 5 and 0.
Thanks in advance,
Dan
You can do something like this:
for ($i = 0; $i < count($_POST['post_values']); $i++){
if (empty($_POST['post_values'][$i])){
$_POST['post_values'][$i] = 0;
}
}
Would this work?
foreach ($_POST['post_values'] as $key=>$test) {
if($test==""){
$_POST["post_values"][$key]=0;
}
};
print_r($_POST['post_values']);
you can do the following. inside your look you can check for value
$value = (trim($test) != "" ? $test : 0);
echo $value; // if $test is blank then it would be 0 else would get value of $test.
Related
I have the following Fiddle set up here Fiddle
As you can see, I am able to add inputs by clicking the Add Row button.
All inputs that are added have a unique id and name. The problem is, I cant just do something like
$actionInput = $_POST["actionInput"];
Because I might need
$actionInput1 = $_POST["actionInput1"];
$actionInput2 = $_POST["actionInput2"];
$actionInput3 = $_POST["actionInput3"];
Depending on how many rows are added. So how can I get all the inputs without knowing what inputs I need to grab?
Thanks
Actually, you need to maintain counter in hidden, which you will get at the time of posting the form in case you don't want to maintain elements as array, otherwise you can put elements as array as described below:
<input type=text name="inputs[]" />
Name your inputs with array boundary, like:
<input type=text name="actioninput[]" />
now you can itreate throught them in you POST or GET ( depends ) array:
print_r($_POST);
Assuming your JSFiddle works fine for you, following are the steps.
1) Get keys of $_POST.
2) Get maximum counter value from keys.
3) Take a for loop from 0 to count of post.
4) If counter is 0, no suffix, else, add counter as suffix.
5) Now, you get posted variable.
6) Repeat it for every element in rows.
<?php
$keys = array_keys($_POST);
$keys = implode(',', $keys);
$n = str_replace('actionInput', '', $keys);
$m = explode(',', $n);
$max = max($m);
for ($i=0 ; $i<=$max ; $i++) {
$suffix = ($i==0) ? '' : $i;
if (isset($_POST['actionInput' . $suffix])) {
echo "<br/>-".$_POST['actionInput' . $suffix];
}
}
replace name=actionInput with name=actionInput[]
it should be an array with same name
same thing will apply with all form fields generated dynamically whose values you'll need.
Change this line in Add row jquery event
return name + i to return name
Remove i from it and then
name=actionInput[]
print_r($_POST);
It will gives array of actioninput
I want to get keys and values from a multi-dimensional array dynamically, to better explain what I'm trying to achieve please see the code below.
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $faq['faq1'][$i];
echo $faq['faq1_answer'][$i];
$i++;
}
The literal text above faq1 and faq1_answer needs to be replaced by the variable $q and $a respectively for me to be able to get the keys and values dynamically, but I cannot figure out how to add the variable.
The keys will always be the same, except for the number, which will change from 1 to 99. So with the code above, I can get the value of faq1 but I also need to grab the value of faq2 etc, hence why the variables above would work as I need.
tl;dr faq1 needs to be able to change to faq2 on the next iteration, hence the reason for me using $i.
Maybe like this?
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $f[$a];
echo $f[$a];
$i++;
}
I have this API that returns this:
{"response":
[{"cid":5122405,"title":"Austin","area":"Estrie","region":"Quebec"},{"cid":5467453,"title":"Austin","region":"Manitoba"}]}
I want to print all areas, but as an example above, Austin in Quebec has area value (Estrie), but Austin in Manitoba doesn't.
My code is:
for($i = 0; $i < count($json_array['response']); ++$i){
echo $json_array['response'][$i]['area'];
but the problem is I get this error Notice: Undefined index: area in... where area value is not present (like Austin in Manitoba).
How can I check is area is present or not?
There's two basic ways to can deal with this problem.
The simplest is to check the existence of the variable
echo array_key_exists('area', $json_array['response'][$i]) ? $json_array['response'][$i]['area'] : null;
The other way is to standardise the response from the API so that the area key always exists
function standardizeApi($values)
{
foreach ($values['response'] as $i => $details) {
if (!array_key_exists('area', $details)) {
$values['response'][$i]['area'] = null; // default value
}
}
return $values;
}
$json_array = standardizeApi($json_array);
// loop though as normal
The second way is better if you have more than one key to check. You can ensure the array contains values, even if the api is missing them.
Edit: Spelling
quick if
for($i = 0; $i < count($json_array['response']); ++$i){
if($json_array['response'][$i]['area']){
echo $json_array['response'][$i]['area'];
};
You can use the json decode as an object and get the item list:
$stringJson = '{"response":[{"cid":5122405,"title":"Austin","area":"Estrie","region":"Quebec"},{"cid":5467453,"title":"Austin","region":"Manitoba"}]}';
$jsonObj = json_decode($stringJson);
foreach ($jsonObj->response as $item) {
echo $item->cid; // 5122405 5467453
}
been trying to figure out the best way to do something. I have the following
$inputParams = array();
if (isset($_POST["inputOne"]) && !empty($_POST["inputOne"])) {
$inputOne = $_POST["inputOne"];
array_push($inputParams, $inputOne);
}
if (isset($_POST["inputTwo"]) && !empty($_POST["inputTwo"])) {
$inputTwo= $_POST["inputTwo"];
array_push($inputParams, $inputTwo);
}
if (isset($_POST["inputThree"]) && !empty($_POST["inputThree"])) {
$inputThree= $_POST["inputThree"];
array_push($inputParams, $inputThree);
}
So, because not all the inputs are required, my array could have 1, 2 or 3 values.
I then come to the part that handles the array, at the moment I have something like
$this->inputOne = $inputParams[0];
$this->inputTwo = $inputParams[1];
$this->inputThree = $inputParams[2];
Obviously this is not a good way to do it, because if one of the inputs is empty (which they can be) then the above will throw an error. I need to assign the values to a variable if they exist though, so what would be the best way to do this? I was thinking a foreach loop, but then I dont know how much control I have over the value being assigned (if only inputOne and inputThree have data, will inputThree be assigned to variable 2?)
UPDATE
If I have
$this->inputOne = (!empty($inputParams[0])) ? $inputParams[0] : 'no data';
$this->inputTwo = (!empty($inputParams[1])) ? $inputParams[1] : 'no data';
$this->inputThree = (!empty($inputParams[2])) ? $inputParams[2] : 'no data';
var_dump("Input One is " . $this->email);
var_dump("Input Two is " .$this->mobNumber);
var_dump("Input Three is " .$this->storeCode);
And I fill in the fields inputOne and inputThree (giving the second one no data), then the output is
string(37) "Input One is myemail#gmail.com"
string(19) "Input Two is ABC123"
string(22) "Input Three is no data"
So the data from input three has been given to input two. Is there any way to stop this happening?
You can user ternary operator to check if variables are empty and assign.
Ofocurse this is for only if you know the number of elements in the array else ARRAY is your best friend
$this->inputOne = (!empty($inputParams[0])) ? $inputParams[0] : '';
$this->inputTwo = (!empty($inputParams[1])) ? $inputParams[1] : '';
$this->inputThree = (!empty($inputParams[2])) ? $inputParams[2] : '';
UPDATE:
You can loop through the $this object and check for properties which has value 'no data' and remove those properties.
foreach ($objects as $key => $value) {
if($objects->key == 'no data'){
unset($objects->key); // This will just remove that property.
}
}
If you have an unknown number of input values, then don't work with separate variables and fields for each, but use arrays all the way through:
<input name="input[]">
<input name="input[]">
<input name="input[]">
<?php
if ($_POST) {
$this->inputs = array_filter($_POST['input']);
}
That's all you need. Gives you an array with as many input values as you got, with empty elements filtered out.
Just for example:
if (isset($_POST["inputThree"]) && !empty($_POST["inputThree"])) {
$inputThree= $_POST["inputThree"];
}
else {
$inputThree = 0; //or some value which you want
}
array_push($inputParams, $inputThree);
Instead of passing the input elements as inputOne, inputTwo and inputThree, pass the data as array using JSON object and parse it back here so you can put these in a loop and process this data in a more elegant way.
Refer for JSON.stringify here : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Refer for json_decode here :
http://php.net/manual/en/function.json-decode.php
Once you have decoded it you can process it as an array like
$inputParams = array();
$inputElems = json_decode($_POST['input_arr']);
foreach($inputElems as $Elem)
{
if (isset($Elem) && !empty($Elem)) {
array_push($inputParams, $Elem);
}
I have this system where I store checkbox data into an array. So if it is checked it will put the value in the array. Let's say that there are 6 checkboxes, and I check the last 3, then array values [3][4] and [5] will have values, correct? Ok.
Now if the array values [0][1] and [2] are 0 as they haven’t been checked, what is their value?
The question is, that when I do a MySQL insert to a database and I use this code?
mysqli_query($con,"INSERT INTO accounts (chk1, chk2, chk3, chk4, chk5, chk6) VALUES ('$checkbox[0]', '$checkbox[1]', '$checkbox[2]', '$checkbox[3]', '$checkbox[4]', '$checkbox[5]'");
Now, when that query executes, if the first arrays are nothing, it will skip them and pretend they are not there. Is there a way I can make them just put 0 if they haven’t been checked.
Why not just apply a DEFAULT 0 constraint to every check{n} field, in the database?
That way, (1) you will make your data protect themselves regardless of the interface and (2) there would be less code to be written, since less checks would be necessary.
put this code before your query
$checkbox[0]=(isset($checkbox[0]))?$checkbox[0]:0;
$checkbox[1]=(isset($checkbox[1]))?$checkbox[1]:0;
$checkbox[2]=(isset($checkbox[2]))?$checkbox[2]:0;
$checkbox[3]=(isset($checkbox[3]))?$checkbox[3]:0;
$checkbox[4]=(isset($checkbox[4]))?$checkbox[4]:0;
$checkbox[5]=(isset($checkbox[5]))?$checkbox[5]:0;
OR
// get $_POST value
function initPostValue($elementVar, $defVal=null) {
if(!isset($_POST[$elementVar])){
$_POST[$elementVar] = $defVal;
}
return $_POST[$elementVar];
}
// get $_REQUEST value
function initRequestValue($elementVar, $defVal=null) {
if(!isset($_REQUEST[$elementVar])){
$_REQUEST[$elementVar] = $defVal;
}
return $_REQUEST[$elementVar];
}
// get $_GET value
function initGetValue($elementVar, $defVal=null) {
if(!isset($_GET[$elementVar])){
$_GET[$elementVar] = $defVal;
}
return $_GET[$elementVar];
}
Example : $checkbox[0] = initRequestValue('checkbox[0]',0);
use above function for get any value take from $_GET,$_POST,$_REQUEST so there are no need to for check empty
if(!isset($checkbox[1]))
$checkbox[1]=0;
They will not have values.
You also want to sanity check them using mysqli_real_escape_string.
I'd do an isset on each checkbox item and set it to 0 if it's not there.
Code example as requested:
$checkbox[0] = isset($_REQUEST['checkboxName']) ? mysql_real_escape_string($_REQUEST[$_REQUEST['checkboxName']]) ? 0 ;
if the value is always 1, then use 1 instead of mysql_real_escape_string($_REQUEST[$_REQUEST['checkboxName']])
$data = array();
for($a=0; $a<max(array_keys($checkbox)); $a++) {
$data["chk$a"] = $checkbox[$a] ?: '0';
}
$sql = 'INSERT INTO accounts (\''.implode('\',\'', array_keys($data)).'\') VALUES ('.implode(',',$data).')';