Put JSON data into html form input checkbox with PHP - php

I want to put json data into html form input checkbox with laravel blade.
I have multiple input checkbox values as test[],
Then I try use htmlspecialchars to print values into input.
If my frontend check this input, backend use print_r is like this
Array
(
[0] => {"value1":"tool_ad_id","value2":"\u65e5\u4ed8"}
[1] => {"value1":"ad_group1","value2":"\u30c4\u30fc\u30eb\u5e83\u544aID"}
)
but I use return $request->test['0']['value1']; can't get a value.
I want to get 'value1' and 'value2'.
PHP Laravel
#foreach($as as $key => $value)
<div class="col s6 m4 l3 blue-grey lighten-5">
<?php
$data = ['value1' => $value['en'] ,'value2' => $value['jp'] ];
$data_total = htmlspecialchars(json_encode($data));
?>
<input type="checkbox" id="test5{{ $key }}" value="{{$data_total}}" name="test[]" />
<label for="test5{{ $key }}">{{$value['jp']}}</label>
</div>
#endforeach
Laravel Controller
return $request->test['0']['value1'];
Error message
Illegal string offset 'value1'

[0] => {"value1":"tool_ad_id","value2":"\u65e5\u4ed8"}
Index => String
PHP does not parse JSON, you are receiving the JSON as normal string. Therefore, in order to convert it to a PHP object with properties correspongind to the keys, you need to use json_decode().
Try $test = json_decode($request->test['0'], true), and then access values off the $test variable.
$value1 = $test['value1'];
$value2 = $test['value2'];

Related

Using null key in html form array

In an html form, it is possible to send data as an array.
<!-- This is an associative array -->
<input name="table[key1]">
<input name="table[key2]">
<!-- This is an index-based array -->
<input name="table[]">
<input name="table[]">
Is it possible to store a value into an associative array, using an empty string as a key?
So that php could access the data with $_POST["table"][null]
null is not an empty string, that would be a '' or a "".
However, PHP will convert it to an empty string and use that as a key (Look under Example 1 at https://www.php.net/manual/en/language.types.array.php)
So these are equivalent:
$a = array('' => 'hello');
$b = array(null => 'hello');
From your example, the data would be in $_POST["table"][""]

PHP $_POST with array and [ ] in key

I have a problem when uploading a list of filenames to php. If the filename contains ] it will break the array decoding in PHP.
It can also be reproduced using $_GET as shown here.
What i want this to be decoded as is:
Array
(
[a] => Array
(
[b[]] => c
)
)
The goal is having a key in an array also containing the ] character
index.php?a[b[]]=c
Gives me this:
Array
(
[a] => Array
(
[b[] => c
)
)
Encoding them gives same problem
index.php?a[b%5B%5D]=c
Gives me this:
Array
(
[a] => Array
(
[b[] => c
)
)
Double encode it does not work either
index.php?a[b%255B%255D]=c
Gives me this:
Array
(
[a] => Array
(
[b%5B%5D] => c
)
)
Is it possible to encode this so PHP will decode it into a array with keys with the string that contains
Referencing my comment. You've put your focus on the wrong side of the table. It's not the handling of incoming information that is the problem, it's your client side submission of the data that isn't correctly passing through data. The brackets are UNSAFE characters to submit through to an endpoint and the client that is submitting this information is where you need to make the changes, not the backend handling the data.
Read up on the safe and unsafe characters in URL's here:
Stop using unsafe characters in URL's
Brackets are used to define nested list data and the way you are attempting to use it breaks that logic, you will have to change the way your frontend (or whatever is doing the HTTP request) encodes that data.
I don't know about your file upload and you need [ - character in filename or not, but problem with the $_GET array I can sloved so:
<? dump($_GET['a']); // Array([b[] => c)
$arr = [];
foreach ($_GET['a'] as $key => &$value) {
$vl = str_replace('[', '', $key);
dump($key); // b[
dump($vl); // b
$arr[$vl] = $value;
}
dump($arr); // Array([b] => c)
?>
Hope it helps you.
If you write a small script, you can ask PHP what it prefers:
<?php
$c = 0;
$data = array(
"a" => array(
"b[]" => $c
)
);
echo "<pre>";
var_export($data);
echo "\r\na[b[]]=c Encoded: " . urlencode("a[b[]]=c");
echo "</pre>";
?>
Results
array (
'a' =>
array (
'b[]' => 0,
),
)
a[b[]]=c Encoded: a%5Bb%5B%5D%5D%3Dc
Update
I wrote the following code just to see how the browser is encoding it:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(function(){
$("form").submit(function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
<label for "a">a[b[]] = </label>
<input type="text" name="a[b[]]" id="a" value="c" />
<br />
<button type="submit">
Go
</button>
</form>
</body>
</html>
When I click Go, I see the following in console:
a%5Bb%5B%5D%5D=c
When I then run it through urldecode():
<?php
echo urldecode("a%5Bb%5B%5D%5D=c");
?>
I see the following results:
a[b[]]=c
So it looks like you do not need to encode the = symbol, but you do want to encode [ and ] properly: %5B and %5D respectively.
So if you want to use:
index.php?a[b[]]=c
I would advise:
index.php?a%5Bb%5B%5D%5D=c
Hope that helps.

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"]')

PHP _GET values in an array

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.

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; ?>">
}

Categories