PHP _GET values in an array - php

I have list of items, after selecting them and pressing a submit button
there's kind of a query in the url bar as such :
adrese-id=7&food-id=1&food-id=2&food-id=3&food-id=4
Trying to get all of the food IDs in an array but no luck so far, tried doing:
$ids = $_GET['food-id'];
but that just has the last value, which is 4...
How do I get those values in an array?

You have to name your field to indicate it's an "array". So, instead of food-id, append brackets to the end to make it food-id[]
For example:
<input type="checkbox" name="food-id[]" value="1"> Pizza
<input type="checkbox" name="food-id[]" value="2"> Cheese
<input type="checkbox" name="food-id[]" value="3"> Pepperonis
Accessing it in PHP will be the same, $_GET['food-id'] (but it will be an array this time).

In php the $_GET array has $key => $value pairs. The 'food-id' in this case is the $key.
Because all your values (1,2,3,4) have the same key: 'food-id' the array looks like this:
$_GET = [
'food-id' => 1,
'food-id' => 2,
'food-id' => 3,
'food-id' => 4,
]
This will always be parsed with the last $key => $value pair being used:
$_GET = [
'food-id' => 4
]
The solution to this is always using unique keys in your arrays.

You really need to provide the HTML fragment that generates the values. However if you look at your GET request the values for food-id are not being submitted as an array which is presumably what you want. Your GET request should look more like:
adrese-id=7&food-id[]=1&food-id[]=2&food-id[]=3&food-id[]=4
which should give you a clue as to how your HTML form values should be named.

Related

JSON encode_decode weird behave PHP

I have array input in HTML Form as below
<select name="age[]" id="ageFrom">..Age Options..</select>
<select name="age[]" id="ageTo">..Age Options..</select>
Upon submission, I am saving data in mysql database as json_encoded value like ["20","25"]
foreach($request->request as $key => $value) {
ProfileSettings::create([
'uid' => $curMID,
'code' => 'preference',
'key' => $key,
'value' => json_encode($value),
'serialized' => 1
]);
});
Now, when it get this value from DB and try to decode it as
$val = json_decode(["20", "25"]) OR json_decode(["20", "25"], true)
My DB returns value like
Then i get an error like
htmlspecialchars() expects parameter 1 to be string, array given
Kindly help me to get 20 and 25 as $val[0] and $val[1]
Thing is, you're calling json_decode on a php array [ ].
It expects a string, which it'll convert to an array.
Perhaps you wanted to use json_encode instead? If so, change your code to:
$val = json_encode(["20", "25"]) OR json_encode(["20", "25"], true)
The problem is that the value coming from the data base is ["20", "25"] and when is inserted in the json_decode() function is interpreted as an array.
To solve the problem insert the value in between double quotes.
$val = json_decode("$result") or $val = json_decode('["20", "25"]')

count() returning wrong value

I am using the following code:
$row_arr=$_POST['row_driver'];
print_r($row_arr);
returns:
Array ( [0] => d1 [1] => d2 [2] => d3 [3] => d5 )
but
echo count($row_arr);
is returning me a value of
1
Any reason why?
Here row_driver is an array being received through a form from a previous PHP page using hidden element property of HTML form. Also,
foreach($row_arr as $driver)
{
//code here
}
is returning:
Warning: Invalid argument supplied for foreach() in
D:\XAMPP\htdocs\Carpool\booking_feed.php on line 36
The issue you are facing is with the fact that $_POST['row_driver'] is not an array.
If you have one hidden HTML input:
<input type="hidden" name="row_driver" value="<?php print_r($rows); ?>">
...then $_POST['row_driver'] would be a string, e.g.:
$_POST['row_driver'] = "Array ( [0] => d1 [1] => d2 [2] => d3 [3] => d5 )";
, and therefore, your count() function results in 1.
This would also explain the second issue you are facing, with foreach(), where the function expects an array, but you are providing a string.
A solution would be to use a foreach loop for your hidden HTML inputs like this:
<?php foreach($rows as $row_driver){?>
<input type="hidden" name="row_driver[]" value="<?php echo $row_driver; ?>"/>
<?php }?>
This would then turn your $_POST['row_driver'] into an array.
You might just store the count value in some variable :
$row_arr=Array('d1','d2','d3','d4');
print_r($row_arr);
$count = count($row_arr);
echo 'Your Count is:- '.$count;
PHP document:
expression
The expression to be printed. return
If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will
return the information rather than print it.
Return Values
If given a string, integer or float, the value itself will be printed.
If given an array, values will be presented in a format that shows
keys and elements. Similar notation is used for objects.
When the return parameter is TRUE, this function will return a string.
Otherwise, the return value is TRUE.
print_r() can use as special printing method to display all values in arrays and for associative arrays(more helpful for this).
Associative array:
Associative arrays are arrays that use named keys that you assign to them.
If you use echo you have print it with a array index. As a example $row_arr[0] or if you use for associative array instead of index, key is used. it may be string.
The problem lies with the hidden field
foreach ($rows as $value){
<input type="hidden" name="row_driver[]" value="<?php echo $value; ?>">
}

query with IF not working

Hi I have some variables which are calculated with API's in an early script but successfully return the value $TotalDistance (based on postcode to postcode driving distances).
I have added a checkbox to tick when it is a return journey, the idea is that it then doubles the distance, this is my query.
if($values['Return']>0) $TotalDistance=2*$TotalDistance; else $TotalDistance=$TotalDistance;
However the result is still returning as a single (x1) value even if checkbox is ticket? Why
I'm assuming this is a HTML form and $values is either a reference to, or built from $_POST.
When submitting a checkbox in an HTML form, there are two possible outcomes:
Unchecked - doesn't get submitted and won't be part of the array
Checked - the VALUE of the checkbox gets submitted
Example:
<input type="checkbox" name="Result" value="MyResultValue" />
<input type="hidden" name="HidValue" value="OtherValue" />
Would yield this when unchecked:
array (size=1)
'HidValue' => string 'OtherValue' (length=10)
And when checked:
array (size=2)
'Result' => string 'MyResultValue' (length=13)
'HidValue' => string 'OtherValue' (length=10)
So, to check if it is checked (I like to include a validation check to make sure the value wasn't changed) do something like this:
$values = $_POST; //again I'm assuming something like this is happening
if( isset($values['Result']) && $values['Result'] == 'MyResultValue' )
If you don't care about the validation - just use the isset.

Pass Hidden Fields with the Same Name. Will PHP Get Them as Array?

If I have a form with hidden fields in this format:
<input type="hidden" name="mydata[]" value="one">
<input type="hidden" name="mydata[]" value="two">
<input type="hidden" name="mydata[]" value="three">
Will I be able to access these three values as an array with $_REQUEST?
Yes. The result should be something like this:
print_r($_REQUEST['mydata']);
array
(
0 => "one",
1 => "two",
2 => "three"
)
echo $_REQUEST['mydata'][1]; // echos "two"
Yes (since the names end in []).
Yes. These values will be in an array and numerated from 0 to n. First input will be always at key 0 and so on.

Random number of FORM fields being prepared for database

I've found myself with the following problem: I have form with a random number of fields. (This is so users can enter their fellow team members's names -- and there's no set size for teams.) I need this inputted data to be formatted in preparation for being stored in a database.
The database structure is fine, it's just getting a random number of $_POSTs and putting them into an array that's the issue.
So far I've got some javascript that allows the user to create/remove an infinite number of fields, with incrementing ids/names (e.g. TeamMemberName1, TeamMemberEmail1, TeamMemberName2, TeamMemberEmail2, etc.).
Right now I've created an ugly series of PHP statements that puts a reasonable amount of POSTed data into a multidimenional array -- I don't see why a team should ever be bigger than 50 -- and then I was going to process the array to remove any blank rows before passing it onto the database.
Example:
$submittedTeamMembers =
array ( "teamMember1" =>
array ( "name" => $_POST["teamMemberName1"],
"email" => $_POST["teamMemberEmail1"])
);
But I'm guessing there's a better way!
Your input names can be in array form, which PHP will understand perfectly. Example:
<input type="text" name="teamMembers[0]['name']" />
<input type="text" name="teamMembers[0]['email']" />
which PHP will interpret after post as you'd expect:
//print_r($_POST['teamMembers']);
Array
(
[0] => Array
(
[name] => foo
[email] => bar
)
)
Just give all your fields a name of 'TeamMemberName[]' or 'TeamMemberEmail[]'. Each should be posted regardless of whether or not the value is there, so they should always match up.
This will pass them as an array to your server-side PHP script, so you can access them like so:
$teamMemberNames = $_POST["teamMemberName"];
$teamMemberEmails = $_POST["teamMemberEmail"];
for ($i = 0; $i < count($teamMemberNames); $i++)
echo "name = {$teamMemberNames[$i]}, email = {$teamMemberEmails[$i]}\n";

Categories