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.
Related
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.
I have read a lot of posts and have not been able to find a solution to my issue.
I have a $_POST array named "Water", $_POST['Water'] and its contents are:
[Water] => Array ( [0] => 55.0 [1] => 22 )
Is it possible to use the name of the post inside a foreach loop so the $key could use the name "Water":
foreach($_POST['Water'] as $key => $val) {
$fields[] = "$field = '$val'";
//echo "Key: $key, Value: $val<br/>\n";
}
Many thanks for your time.
Not really. foreach() operates on the contents of an array. Whatever actually contains that array is outside of foreach's view. If you want to dynamically use the Water key elsewhere, you'll have to do that yourself:
$key = 'Water'
foreach($_POST[$key] as $val) {
$fields[] = "$key = '$val'";
}
If I read this right you basically want $field='water' inside the foreach. This can be done be rethinking the way we build the foreach.
You simply need to make the field value a variable and pass use that rather everywhere the value is needed.
$field = 'Water';
foreach($_POST[$field] as $key => $val) {
$fields[] = "$field = '$val'";
//echo "Key: $key, Value: $val<br/>\n";
}
The advantage of this approach is that if you change your mind and the $_POST key is later called, "liquid" one single line needs to be edited and that is all. Furthermore, if your foreach were part of a function $field could be a function parameter. In a roundabout way, you are actually getting pretty close to some code reuse principles.
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;
}
}
I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.
What would be the best way to loop through those items to get the values?
Here's what I have, which obviously isn't working.
extract($_POST);
$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop
while(${'item_name_' .$x} != '') {
echo ${'item_name' .$x};
$x++;
}
I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.
Thanks.
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
CodeIgniter allows access to POSTed data via:
$this->input->post('input_name');
where 'input_name' is the name of a form field. This works well for a static form where each input name in known ahead of time.
In my case, I am loading a collection of key/value pairs from the database. The form contains a text input for each key/value pair.
I am wondering, is there a way to get an array of posted data via the CodeIgniter api?
Thanks!
According to the documentation, no. I would suggest just using array_keys($_POST) to get the keys.
foreach($this->input->post() as $key => $val) { echo "<p>Key: ".$key. " Value:" . $val . "</p>\n"; }
that can be used to
Surely if you have an array of keys from the database you can use that, like :
foreach ($arrayFromDb as $key => $value) {
$newValue = $this->input->post($key);
}
Then you have the advantage that people if people submit additional fields (e.g. by modifying the form and posting it themselves) those fields will be ignored
$array_db_columns = $this->db->query('SHOW COLUMNS FROM ci_props');
$array_db_columns = $array_db_columns->result_array();
$array_save_values = array();
foreach ( $array_db_columns as $value )
{
$array_save_values[$value['Field']] = $this->input->post($value['Field']);
}
insert :
$this->db->insert('props', $array_save_values);
update :
$this->db->where('id',$id); $this->db->update('props',$array_save_values);