multiple textarea with same name and PHP treatment - php

I have a dynamic form in which i can add and remove textarea.
The name of textareas is MyTextarea[]
<textarea style="display:inline;" name="MyTextarea[]"></textarea>
<textarea style="display:inline;" name="MyTextarea[]"></textarea>
So when I want to treat this textarea with PHP i'm doing a :
echo $_POST['MyTextarea'];
So a Array is display on the screen, up to now it's ok
So I do a print_r($_POST['MyTextarea']); and I have again the same result : Array
I want to know if it's possible to have many textarea with same name with [] to generate an array.
If it's possible how can I do, or what's wrong with my code.
Thanks

Yes, in php if you have an input field with a name like this "MyTextarea[]" is posted as an array.
So if you want to access your data, you have to do:
echo $_POST['MyTextarea'][0];
If you have multiple textareas with the same name, you'll get an array where each index has one textarea. The first textarea in the form is the first textarea in the array
you could do
foreach ($_POST['MyTextarea'] as $textarea){
//do wat you need
}
This is obviously a killer feature to use if you need to add multiple textareas dinamically.

Which kind of framework are you using, I'm quite sure there is something at one point that is casting you're array into a string, maybe something that apply a treatment on POST variable like this:
foreach ($_POST as $key => $value) {
if ($value && !$is_magic_quotes_gpc) {
$_POST["$key"] = addslashes($value);
}
In this case you've to remove this function...
To be sure of what I'm talking about, you can try a var_dump($POST[MyTextarea]) =>string 'Array' (length=5) (should be an array)

Related

php $_POST variable variables

I am trying to populate an HTML form with values from a previous form being posted. The first form is created dynamically and is a list of t-shirt styles with 5 different sizes available.
I'm having trouble figuring out a way to populate the second form.
The HTML is this:
echo '<input name="'.$filename.'-s" type="text" size="3" value="'.$quantity.'"'>;
What I'd like to do for $quantity is something like this:
$quantity = $_POST['{$filename.$size}'];
Is it possible to use a variable with $_POST?
I think you're looking for this:
$quantity = htmlentities($_POST["$filename$size"]);
htmlentities() is necessary in case you have " or other junk in the input
$_POST[$var1.$var2] worked. Nothing came up in my initial search of previous answers, although I see several applicable questions in the related questions on this page.

Return results from form as split array

I'm trying to customize an existing opensource script and ran into a snag. In the processing file, I'm using the following line to retrieve the user's input from a form they submit.
$listingKeywords = $_POST["listingKeywords"];
The user is asked in the form to enter the keywords with a comma in between each one (example: Keyword One, Keyword Two). Within the processing file, I have the following...
$keyword_list = array(
'1'=>"HTML5",
'2'=>"CSS3",
'3'=>"PHP",
);
This is being used later on like so:
foreach ($keyword_list as $key=>$value)
Basically I'm looking for a way to split $listingKeywords by comma and then set the $key via $i++. I know it's simple and I'm just asking for someone to point me in the right direction.
Thanks!
$arr = explode("," $content);
is this what you want?
Just remember to use trim before putting them into a database, people well tend to do use value1, value2, value3

HTML checkbox form and HTTP URL

So, I have this HTML form:
<form id="search_form" class="form_wrapp"
accept-charset="utf-8" method="get" action="http://testing.com/results">
<input class="inputbox" type="text" name="search_query">
<input class="ic_search" type="submit" value="">
<input type="checkbox" value="checkbox1" name="search_filter[]">
<label for="Checkbox1">Checkbox1</label>
<input type="checkbox" value="checkbox2" name="search_filter[]">
<label for="Checkbox2">Checkbox2</label>
</form>
and it redirects to this URL upon submit with the 2 checkboxes checked
results?search_query=dreams&search_filter[]=checkbox1&search_filter[]=checkbox2
It works like this (inside codeigniter I get the data with $this->input->get('search_filter')), but my question is: I am doing something wrong inside the form, or this is how it's supposed to work?
And I mean about: &search_filter[]=checkbox1&search_filter[]=checkbox2. Shouldn't it be something like: &search_filter[]=checkbox1,checkbox2 ? And if not, how can I make it work like that?
If you want it in the comma format you can do the following:
$filters = (array) $this->input->get('search_filter');
$filters = implode(',',$filters);
If you want to alter the format in which the form is submitted, assuming jquery for js:
$('#search_form').submit(function() {
var $hidden = $('<input type="hidden" name="search_filter" />').appendTo($(this)),
$filters = $('input[name^=search_filter]'),
value = '';
//loop through the filters check if there checked and add them to the value
$hidden.val(value);
$filters.remove();
});
Of course if the user doesn't have js enabled it will submit natively
Am I doing something wrong inside the form, or this is how it's supposed to work?
That's how it's supposed to work. At least if you need to read query string with PHP, those brackets need to be there to read the whole query string without each search_filter value being overwritten by the next one.
And if not, how can I make it work like that?
If you have to, you can use a POST request instead, process the submission, and redirect to the URL of your choice with whatever query string you want.
From your comment:
I wanted to make the url like this &search_filter[]=checkbox1,checkbox2 just to make it a bit more "beautiful"
Don't worry about that, seriously. The only time this matters is when you're doing extreme SEO and you don't want two URLs that point to the same place. It's common practice in those cases to remove all unused keys and alphabetize them so that all URLs with query strings are consistent, but mangling them into something custom still isn't a part of that.
Besides that, don't fight against the behavior - work with it - it's not "broken" and making it "beautiful" won't matter to anyone, plus you'll have to guess/remember which pages process query strings the correct way, and which ones use your "custom" method.
I am doing something wrong inside the form, or this is how it's supposed to work?
That is how it is supposed to work
Shouldn't it be something like: &search_filter[]=checkbox1,checkbox2 ?
Then you couldn't tell the difference between two items and one item that had a comma in it.
And if not, how can I make it work like that?
Obtrusive JavaScript. Don't do that. Forms work well the way they work.
That's perfectly normal. form data is always sent in key=value pairs, with one single value. Submitting key=value,value is not part of the HTTP spec, and would have the values treated as a single monolithic string, not two separate comma-separated values.
You can certainly use some JS to rebuild your form on the fly to use the value,value format, but then you'll have to mod your server-side scripts to accept that new format as well. PHP won't auto-split the values before you, because it's not a standard representation.
&search_filter[]=checkbox1,checkbox2
Why you need this?
Use this like:
<?php
$searchFilter = $this->input->get('search_filter');
foreach($searchFilter as $filter)
// some actions with filters.
You search_filter[] is simple array with values from checkbox inputs.

PHP pass a string containing quotations via GET

I am trying to pass a string that already contains quotation marks from one php file to another via a hyperlink and the GET method.
I am retrieving thousands of lines which contain quotation marks in a while loop and saving the output to a variable as follows:
while ($trouble_row = mysql_fetch_array($trouble_result)) {
$ticketid = $trouble_row['ticketid'];
$ticketno = $trouble_row['ticket_no'];
$created = $trouble_row['createdtime'];
$modified = $trouble_row['modifiedtime'];
$title = $trouble_row['title'];
$solution = $trouble_row['solution'];
$hoursattended = $trouble_row['cf_629'];
$hoursbilled = $trouble_row['cf_628'];
$csv .= "$firstname $lastname,$ticketno,$created,$modified,$hoursattended,$hoursbilled,$title,$solution\n";
}
The variable $title sometimes contains an entry that looks like this:
The user "tom" is having problems.
The variable $csv is collecting all the results from each pass and creating a CSV formatted string that I then need to pass to a new php script, which I am trying to do using a hyperlink:
a href="export_csv.php?csv=$csv">Export to CSV</a>
Unfortunately the embedded quotation marks are recognized by the hyperlink and cut off the majority of the output. Any suggestions on how to collect the data differently, store it differently, or pass it differently would be greatly appreciated!
For parameters in links, you need to use urlencode():
echo 'Export to CSV';
note however that GET requests have length limits starting in the 1-2k area (depending on browser and server).
Alternative approaches:
Forms
One method that is immune to length limits is creating a <form> element for each link with method="post" and adding the values in <input type='hidden'> inputs. You would then style the submit button of the form like a link.
<form action="export_csv.php" method="post">
<input type="hidden" name="csv" value=".......">
<button type="submit">Click here </button> <!-- Use CSS to style -->
</form>
Sessions
Another very elegant way to pass the data would be
Generating a random key
Saving the CSV data in a $_SESSION variable with the random key
Passing the random (short) key in the URL instead of the full data
You'd just have to take care of deleting unused random keys (and their data) frequently.
These kinds of links couldn't be bookmarked, of course.
Use urlencode() before creating the hyperlink url, and use urldecode() to get the original string.
use urlencode() for embedding into a link, and html_special_chars() for embedding into form fields.
url_encode and url_decode.
Quickest and easiest solution given what you already have is probably to change this:
Export to CSV
To something like this:
Export to CSV

Storing Form Text Fields as Array within $_POST variable

I'm creating an HTML form using jQuery that has certain text boxes grouped together under a single question (e.g., "List each URL that this request applies to.") For that question (and others), there are 3 text boxes below it along with a button to add additional text boxes if necessary. When I pass this form data to be processed by PHP, how can I have all these text box values be grouped together as a single array variable within the $_POST array variable? I tried giving all the text boxes the same name attribute followed by brackets, but that didn't seem to work (e.g., <input name='myarray[]' type='text' />). Any suggestions?
EDIT: Here are the specifics on the error I'm getting:
I'm using this in PHP
$myarray ='';
foreach ($_POST['myarray'] as $value) {
$myarray .= $value . '\n';
}
The error I get is:
"Warning: Invalid argument supplied for foreach()"
foreach($_POST["myarray"] as $myarray)
{
echo $myarray . "";
}
This is quite simple. I suppose you are using $_POST['myarray[]'] (notice brackets[]) which is incorrect. This example should work perfectly fine.

Categories