How to create Json objects from foreach $_POST loop - php

i have made some random input names, because its a drag and drop page builder, so i can't guess, how much elements user will use, so i have created a random input names,
for that am using php foreach loop for $_POST requests. i have tried to make it encoded into json and then later save it into database. but it looks like something is wrong in my json.
Here are my html demo codes :
<input style="display:none;" name="DATA-BLOCK-A(some random string)">
<input style="display:none;" name="DATA-BLOCK-B(some random string)">
PS: A is for selecting element A, and B is for element B.
here is my PHP code :
if (isset($_POST)) {
//$arr = array();
foreach($_POST as $key => $value)
{
$arr = array($key => $value);
$encode = json_encode($arr);
echo $encode;
}
}
and Here is the result :
{"sortlist":"block[]=D5e3385b75a75d&block[]=K5e3385b85a75e&block[]=C5e3385b95a75f&block[]=F5e3385ba5a760"}{"save_cont_flag":"0"}{"DATA-block-D5e3385b75a75d":"0#TRANSP
<\/p>"}{"DATA-block-K5e3385b85a75e":"0#TRANSP20"}{"DATA-block-C5e3385b95a75f":"01#TRANSP0images\/250place.jpg\u00b8"}{"text-1573532276681":""}{"textarea-1573532278320":""}{"DATA-block-F5e3385ba5a760":"121212unundefined"}{"page_name":"123"}{"aff_link":""}{"pause_link":""}{"seo_title":""}{"fbook":""}{"seo_desc":""}{"seo_keywords":""}{"back_color":"#EEEEEE"}{"body_color":"#FFFFFF"}{"back_image":""}{"ty_font_color":"#000000"}{"ty_override":""}{"ty_name":"12314"}{"ty_stm":""}{"modal_para_width":"0"}{"catcha_url":""}{"catcha_un":"Yes"}{"catcha_message":""}{"code_head":""}{"code_body":""}{"modal_share_width":"0"}{"modal_cta_width":"0"}{"modal_video_width":"0"}{"modal_mp_width":"0"}{"modal_stm_width":"0"}{"modal_image_width":"0"}{"modal_bonus_width":"1"}{"ty_headline":""}{"modal_spacer_width":"0"}{"att_bar_status":"0"}{"att_delay_in":"0"}{"att_bar_color":"#bbbbbb"}{"att_gradient":"0"}{"att_text_color":"#000000"}{"att_text_font":"Open Sans:400"}{"att_text_size":"14"}{"att_bar_message":"Add Your Attention Bar Text Here"}{"att_link_color":"#000000"}{"att_link_label":"Add Link Text Here"}{"att_link_url":"http:\/\/commissiongorilla.com"}{"count_font":"Open Sans:800"}{"count_size":"55"}{"count_status":"0"}{"count_type":"0"}{"count_end":"01\/31\/2020 6:41 AM"}{"count_zone":"0.0"}{"count_eg_days":"0"}{"count_eg_hours":"0"}{"count_eg_mins":"0"}{"count_digit_color":"#bbbbbb"}{"count_label_color":"#bbbbbb"}{"count_background":"0"}{"count_language":"1"}{"count_exp":"0"}{"count_url":"http:\/\/commissiongorilla.com"}{"count_add_days":"0"}{"count_add_hours":"0"}{"count_add_mins":"0"}{"modal_countdown_width":"0"}{"modal_review_width":"0"}
and also how seperate all A BLOCKS and B BLOCKS?
Thanks.!

You don't need to use a loop.
Just used json_encode :
$json = json_encode($_POST);
If you need to get key contain DATA-block-, you can write :
foreach ($_POST as $key => $value) {
if (strpos($key, 'DATA-block-') !== false) {
// Here `DATA-block-{}`
}
}

If you change the input names to DATA-BLOCK-A[] and DATA-BLOCK-B[], $_POST['DATA-BLOCK-A'] will contain an array of all a blocks and $_POST['DATA-BLOCK-B'] will contain an array of all b blocks.
This also eliminates the need for generating random strings.

Related

output values from array into variables in php

I have 2 pages in php. The 1st page includes a form which transimts data to the 2nd page. The form uses method=post. Data transmitted successfully in the 2nd page. I have the following code, which gets data and printing them using the code:
php?
var_dump($_POST);
foreach ($_POST as $key => $value) {
echo $value;
}
?>
All I want is to extract data from array and place them into variables, because I want to use these varaibles later in some if startments and mysql queries. Any idea how can i do this?
First, these really are basic PHP skills (or programming skills for that matter). Try to follow some tutorials or courses before attempting to write code in the "real world".
As long as you know the key for the value you want to store, this is how you do it:
$yourVariableName = $yourArray['yourKey']; // or just a number if the key is an int
You don't need for loops to do this.
EDIT
$kentroName = $_POST['kentro_name'];
$kentroSurName = $POST['kentro_surname'];
// And then the following six.
<?php
var_dump($_POST);
$array = array();
foreach ($_POST as $key => $value) {
echo $value;
$array[$key] = $value;
}
print_r($array);
?>

PHP post all form inputs without creating variables for each

Usually when I use PHP I create a variable and post statement for each form input like so:
$myVar1 = $_POST["formItem1"];
$myVar2 = $_POST["formItem2"];
ect......
I know if i use:
echo $_POST;
I can get all the key and values from the form inputs but I don't know how to use them in a script.
So I guess I have 2 questions:
How do I quickly post all form inputs without creating a variable for each input?
How do I use a posted in a script without having it assigned to a specific variable?
To simply echo all the inputs, you can use a foreach loop:
foreach ($_POST as $key => $value) {
echo $value.'<br/>';
}
If you don't want to store them in variables, use arrays:
$data = array();
foreach ($_POST as $key => $value) {
$data[] = $value;
}
Now, $data is an array containing all the data in $_POST array. You can use it however you wish.
You don't have to assign to a variable. You can use directly $_POST['input_name']
If you want to deal with each sended params, you can use foreach loop:
foreach ($_POST as $key => $val)
{
echo "$key : $val <br/>";
}
for this instance of just quickly checking and testing i typically just use the print_r() function: documentation here
as quoted from the docs:
print_r() displays information about a variable in a way that's readable by humans.
one line easy to toggle on and off (with comments)- no need to use any form of variables
print_r($_POST);
if i need my output nice and readable i like to expand it as follows:
function print_r2($x){
echo '<pre>';
print_r($x);
echo '</pre>';
}
and then you can call with: print_r2($_POST);
this way you get the pre-formatted text block on your html page and can see the line breaks and tabbed spacing provided from the $_POST object printout
Another way to extract (besides the extract function) variables is;
$array = array('foo'); // Which POST variables do you want to get
foreach($array as $key) {
if(!isset(${$key})) { // Check if variable hasn't been assigned already
${$key} = $_POST[$key];
}
}
echo $foo;
I would not recommend it because it can get quite messy to keep up.
View everything in $_POST is useful for debugging
echo '<pre>'.print_r($_POST, true).'</pre>';
Access a specific checkbox
HTML
<input type="checkbox" value="something" name="ckbox[]" checked>
<input type="checkbox" value="anotherthing" name="ckbox[]" checked>
PHP
echo $_POST['ckbox'][0]; // something
echo $_POST['ckbox'][1]; // anotherthing
// isolate checkbox array
$ckbox_array = $_POST['ckbox'];
Define a function that allows you to access a specific $_POST item by name (key):
function get_post_value($name, $default)
{
if ( isset($_POST[$name]) ) {
return $_POST[$name];
} else if ( $default ) {
return $default;
}
return null;
}
$default allows you to pass a value that can be used as a fallback if the key you specify isn't present in the $_POST array.
Now you can reference $_POST items without assigning them to a variable, and without worrying if they are set. For example:
if ( get_post_value('user-login-submit', false) ) {
// attempt to log in user
}
You can use extract($_POST), it will create variables for you.
For example, you can have for the code you posted :
<?php
$_POST["formItem1"] = "foo";
extract($_POST);
echo $formItem1; // will display "foo"
?>
EDIT : it's not PHP explode, it's extract.

Using form inputs in PHP to populate nested objects

I am trying to process the submitted results for a form, containing data for a number of employees. The form inputs have names like "employees[1]_firstName" which needs to map to the PHP variable $companydata->employees[1]->firstName
When populating the $_POST array, PHP sees square brackets, and tries to make a multi-dimensional array, but gets it wrong (ignoring everything after the opening bracket)
This replicates $_POST but without the corrupted array keys: Note that I've taken out a foreach loop to simplify the question.
$post_data = explode('&', file_get_contents("php://input"));
// Result: $post_data = array('employees%5B1%5D_firstName=Timothy'
list($key, $value) = explode('=', $post_data[0]);
$key = urldecode($key);
$value = urldecode($value);
// Result: $key = 'employees[1]_firstName', $value = 'Timothy'
However things go wrong when I try to use variable variables:
$post_key_parts = explode('_', $key);
// Result: $post_key_parts = array([0] => 'employees[1]', [1] => 'firstName')
$Companydata->$post_key_parts[0]->$post_key_parts[1] = $value;
// Expected result: Element [0] in array $employees => 'Timothy'
The actual result is a variable with square brackets in its name '$employees[0]',
and no change to the $employees array. Putting curly brackets round the {$post_key_parts[0]} doesn't help.
I am trying to find a flexible solution that will also work for names of different lengths eg: employees[0]_address_lines[2] or employees[0]_addresses[1]_postcode
I'm happy to avoid the sin of variable variables, but I can't think of an elegant way to do it with regexes or something like that.
I would suggest you change the inputs' names. To make use of the built-in features of PHP. [] creates an array for you, use arrays then, as you are intended to use them.
I had the same problem and came up with this:
//HTML part
<input name="employee_firstName[]">
<input name="employee_address[]">
//PHP part
<?php
$info = array("firstName", "address")
foreach ($info as $i) {
foreach ($_POST["employee_".$i] as $k => $v) {
$companydata->employees[$k]->$i = $v;
}
}
?>
NOTE I don't think you can do this for things like employees[0]_address_lines[2]. Or maybe try employees[0][address_line][] and use it as an array, but I'm not sure that works.

Parsing unknown POST args in PHP

I have an HTML form being populated by a table of customer requests. The user reviews each request, sets an operation, and submits. The operation gets set into a POST arg as follow
$postArray = array_keys($_POST);
[1]=>Keep [2]=>Reject [3]=>Reject [4]=>Ignore ["item id"]=>"operation"
This is how I am parsing my POST args, it seems awkward, the unused $idx. I am new to PHP, is there a smoother way to do this?
$postArray = array_keys($_POST);
foreach($postArray as $idx => $itemId) {
$operation = $_POST[$itemId];
echo "$itemId $operation </br>";
// ...perform operation...
}
foreach ($_POST as $key => $value) // $key will contain the name of the array key
You could use
foreach($_POST as $itemId => $operation ) {
echo "$itemId $operation </br>";
// ...perform operation...
}
instead
http://nz.php.net/manual/en/control-structures.foreach.php
You don't have to use $idx in loop if is not needed.
It might be like that:
foreach($postArray as $itemId) {
...
}
Main problem is the data structure is very messy.
Maybe it's better way to organise form output.
Probably in some well structured associative array.
I can't see the form, I don't know the details so it's hard to tell more.

ow to handle possible duplicate array keys

I am trying to figure out how I can handle possible duplicate array keys.
I have this form with a select dropdown which can select multiple options (more than 1). And I am using jQuery.serialize() to serialize the form on submit.
The serialized string for a multi-select element would look like so:
select=1&select=2&select=3 // assumming I selected first 3 options.
Now in the PHP side, I have the following code to handle the "saving" part into a database.
$form_data = $_POST['form_items'];
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
$arr[$key] = $value;
}
Ok this all works for the rest of the form elements but when it comes to the select element, it only picks the last selected key/value pair. So my array now looks like this:
Array ( [select_element] => 3)
What I need, is for it to look like:
Array ( [select_element] => '1,2,3')
So I guess what I am asking is based on my code, how can I check if a key already exists and if it does, append to the $value.
If you can modify the client-side code, I would rather change the name of the select to select[], that way it will be parsed as an array in your server script.
You can't have multiple keys with the same name... They're unique keys. What it's doing is setting select = 1, then select = 2, then select = 3 and you end up with your final value of 3.
If you want to allow multiple choices in your select menu, you should change the name of the element so that it submits that data as an array, rather than multiple strings:
<select name="select[]" multiple="multiple">
which should result in something like this instead:
select[]=1&select[]=2&select[]=3
and when PHP requests that data, it will already be an array:
$data = $_POST['select'];
echo print_r($data); // Array(1, 2, 3)
PHP has its own way of encoding arrays into application/x-www-form-urlencoded strings.
PHP's deserialization of x-www-form-urlencoded is implemented by parse_str(). You can think of PHP as running these lines at the beginning of every request to populate $_GET and $_POST:
parse_str($_SERVER['QUERY_STRING'], $_GET);
parse_str(file_get_contents('php://input'), $_POST);
parse_str() creates arrays from the query string using a square-bracket syntax similar to its array syntax:
select[]=1&select[]=2&select[]=3&select[key]=value
This will be deserialized to:
array('1', '2', '3', 'key'=>'value');
Absent those square brackets, PHP will use the last value for a given key. See this question in the PHP and HTML FAQ.
If you can't control the POSTed interface (e.g., you're not able to add square-brackets to the form), you can parse the POST input yourself from php://input and either rewrite or ignore the $_POST variable.
(Note, however, that there is no workaround for multipart/form-data input, because php://input is not available in those cases. The select=1 and select=2 will be completely and irretrievably lost.)
Ok, I was able to resolve this issue by using the following code:
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
So now the loop looks like this:
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
}
This will essentially string up the value together separated by a comma which can then be exploded out into an array later.
You should change your client-side code to send the augmented value: array.join(","); and use that in your PHP side. Because when your data reaches your script, the other values have already been lost.
This should give you the solution you require
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (isset($arr[ $key ])) {
$arr[$key] = ','.$value;
} else {
$arr[$key] = $value;
}
}

Categories