Processing multiple input fields with codeigniter? - php

The problem I am having is that my ecommerce script allows people to add products to their store. However, those products can have variants... like Color and those variants can have options, like Black, White, and Blue for example. The problem I am having is how exactly do I determine how many options they have entered. Eventually I will have a javascript function add a new input field if they click "add option" but for now I just made 3 input fields like so:
Variant Title:<input type="text" name="variant_title"><br>
Variant Option: <input type="text" name="variant_option_1"><br>
Variant Option: <input type="text" name="variant_option_2"><br>
Variant Option: <input type="text" name="variant_option_3"><br>
Now what I don't know how to do is loop through all the variant_options and if they are not empty add them to a database. I don't want to hard code it in with the names because I don't know how many options they will choose per variant.
I tried doing this:
$i = 1;
while($this->input->post('variant_option_$i') != '')
{
$variant_options[] = $this->post->input('variant_option_$i');
$i++;
}
But that does not seem to work, as the variant title gets added to the database, however the options do not.
The only thing I need a solution to is to how to actually grab those fields all at once. I was thinking a foreach loop but im not sure.
Thank you.

I would use an array of input fields instead:
Variant Title:<input type="text" name="variant_title"><br>
Variant Option: <input type="text" name="variant_option[]"><br>
Variant Option: <input type="text" name="variant_option[]"><br>
Variant Option: <input type="text" name="variant_option[]"><br>
Then check for the values like:
if (is_array($this->input->post('variant_option')):
foreach ($this->input->post('variant_option') as $value):
$variant_options[] = $value; // loop through...
endforeach;
endif;

Related

accessing dynamic variables from a form

I used to have register_globals turned ON (I know - bad bad bad horribly bad) and now I'm changing it up and the specific application is my DVD collection. Adding a DVD presents a set of checkboxes for genres/categories (i.e. drama, comedy, etc). Each genre is coming out of a database table so I can add new genres as needed. The problem here is that it generates its fieldname (checkbox name) from an abbreviation in this db table.
IE I'll have:
<input type="checkbox" name="drama" />Drama
<input type="checkbox" name="bio" />Biography
(etc)
So what I was doing before was, with the script that made the entries, it would run through the list of abbreviation names and if it matched the input ($_POST['drama']), it would indicate that this DVD falls into that category.
The present problem now is, with global variables turned off, how can I dynamically gather those $_POST values? I tried looping through the database and spitting out a concatenated variable trying to declare them in this format:
$drama=$_POST['drama'];
This didn't work because I'm mixing up functions with variables and it made a horrible mess.
I hope someone has an answer on how I can read in the $_POST array and use it.
Given some checkboxes like this:
<input type="checkbox" name="genre[]" value="drama" />
<input type="checkbox" name="genre[]" value="comedy" />
<input type="checkbox" name="genre[]" value="mystery" />
you'd end up with $_POST['genre'] being an array. Asuming drama and mystery are checked off, you'd end up with
$_POST['genre'] = array(
0 => 'drama',
1 => 'mystery'
);
Remember that unchecked checkboxes do not submit with the form, so if you get an entry in $_POST['genre'], it was selected in the form.
To check if a category in your DB was selected, you could do something like
if (in_array('drama', $_POST['genre'])) {
... drama is selected
}
See this example:
foreach ($_POST as $key => $value) {
echo "name: $key, value: $value<br />";
}

PHP, Submitting a two dimensional table with TextBox to proccess

I am building an application which has a dynamic table, everytime you open the page table`s row and columns changes based on data in database.
Each Row is a vendor company each colomn is a Item Title. All these vendors upply the same item, So this table has a textbox in each contains a TextBox so user can type the value, which represents the amount of fruit they want from that supplier. the following is the example.
So what I need to do now is, after entering these values, I'd like to process them through PHP, and then see 4 different reports at the confirm page, example: write the Company name and under that, what they have to supply for each item, then the next company, so on and so forth to the end.
I don't know if i should create different class for each textbox? or ID them!! SHould I Array them? I am confused.. If any of you guys can help, would be wonderful
Thanks a lot
I would suggest you just name the input elements as an array. something like:
<input type="text" name="fruits[company1][apple]">
<input type="text" name="fruits[company1][berries]">
<input type="text" name="fruits[company1][orange]">
<input type="text" name="fruits[company1][bannana]">
<input type="text" name="fruits[company2][apple]">
<input type="text" name="fruits[company2][berries]">
<input type="text" name="fruits[company2][orange]">
<input type="text" name="fruits[company2][bannana]">
or the same thing with the fruit being the first level and company name being second. It is really the same thing and generally just as easy to use either one. Just depends on how you want to loop over the data once you post the form. You might be better off also using ids for the company name and/or the fruit. Just makes it so, for example, company names with a space are still valid.
Using the above form, you can process the data with something like this:
<?php
foreach($_POST['fruits'] as $company=>$row){
foreach($row as $fruit=>$quantity){
if(!is_numeric($quantity) || $quantity < 0){
$quantity = 0;
}
echo "You selected {$quantity} {$fruit} from {$company}";
}
}
I would try creating a multi dim array with the ID of the item as the first dimension. Like this:
<input type="textbox" name="textbox[<?php echo $row['item_id']; ?>]["apple"]" value="<?php echo $row['apple']; ?>" />
Then, in your processing script:
foreach ($_POST['textbox'] as $row)
{
foreach ($row as $key => $val)
{
$q = "update `items` set `apple` = {$val['apple']} where `item_id` = {$key}";
mysql_query($q);
}
}

autofill this html field?

what would be the easiset way to autofill this field??
<input type="text" name="start_price" value="<?=$item_details['start_price'];?>" size="8"></td>
i need to keep the $item_details because it gets passed to some other code, but in some cases i want to autofill this as 0.00 to make it easier for me as i will be using 0.00 to list some auctions
i am editing a template that is being used by php to generate some code, so ideally i just want to make some changes to the templates without having to dive into the code itself
Something like this sounds like it might solve your problem:
<?php
// Whatever logic determines a "special case" stores a boolean value
// into the variable $special_case
$input_value = !$special_case ? $item_details['start_price'] : '0.00';
?>
<input type="text" name="start_price" value="<?php echo $input_value; ?>" size="8">

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

PHP multiple radio buttons

how can i process all radio buttons from the page?
<input type="radio" name="radio_1" value="some" />
<input type="radio" name="radio_1" value="some other" />
<input type="radio" name="radio_2" value="some" />
<input type="radio" name="radio_2" value="some other" />
this buttons will be added dynamically so i will not know the radio buttons name(and also the number of the buttons). Is there a way to get all radio values, with a for loop or something like this? thanks
Use a foreach loop
<?php
foreach ( $_POST as $key => $val )
echo "$key -> $val\n";
?>
$key will be the name of the selected option and $val, well, the value.
Since the browser will just change all your input to HTTP-formatted form data, you won't be able to tell what data is from a radio button versus a text box or other input.
If the naming convention is the same as your example, just loop until you don't find a value:
<?
for ($idx = 1; $idx <= 1000; $idx++) {
if (isset($_REQUEST["radio_$idx"])) {
// handle value
}
}
?>
EDIT Alternatively, if your form is generated dynamically, you could write the number of radio buttons it created as a hidden field in the form.
If you are able to alter the form that is being generated, you could write a hidden input that provided a list of all the radio buttons that you want to look for. As you are writing the radio buttons, just make a semi-colon-separated list of all the names that you make. When you are done, write that to a hidden input. Something like this:
On the source form:
<input type="hidden" name="radio_button_list" value="some_value;other_value" />
Then in your handler:
<?
$list = explode(';', $_REQUEST['radio_button_list']);
foreach ($list as $name) {
$value = $_REQUEST[$name];
// handle name & value
}
?>
jheddings' example says it all. However, you will never get the names / values of all buttons - just the selected one from each group. If you need literally all values, you will have to use Javascript.

Categories