How to retrieve information from Check Box? - php

My problem is a little bit complicate. (I use PHP)
I have two arrays, (simple arrays array[0] = string, array[1] = string...)
OK, now I will display the content of two arrays in a webpage.
The first array contain names and the second images URL.
Images and names are already displayed (my problem isn't here).
But now I want to do something else, add a check box near every image, those checkbox r active by default. Ok, now the user can uncheck some inbox;
The final aim, is to get a new array containing only the values of the names and images that had been checked.
I have thought of something simple, crawl the keys (number) of unchecked checkboxes and unset them from my array. But the problem that I didn't know how to deal with the check boxes

To receive inputs as arrays in PHP, you have to set their name using brackets in HTML:
<label><input type="checkbox" name="thename[]" value="" /> The text</label>
Then, when you access $_REQUEST['thename'] you'll get an array. Inspect it to see its format and play with it :)

first of all i recomend having just one array:
$array = array (0 => array('name' => '....', 'url' => '....'))
i think this will make your life much easier.
Also in the HTML you could also send the array key
foreach ($yourArray as $key=>$value) {
...
<INPUT type="checkbox" name="chkArr[<?php echo $key ?>]" value="1" checked/>
then in your form action you itarate the intial array and remove the unchecked ones.
foreach ($yourArray as $key=>$value) {
if (!isset($_POST['chkArr'][$key]) OR $_POST['chkArr'][$key]!='1') {
unset($yourArray[$key]);
}
}

<INPUT type="checkbox" name="chkArr[]" value="$num" checked/>
After the form is submitted, you'll have array $_REQUEST['chkArr'], in which you'll have numbers of the checkbox that are still checked.
To see which have been unchecked use array_diff($listOfAllNums, $chkArr)

Related

Checkbox Values stored in DB and want to display

Please see this link
http://thedesigningworld.com/bea
Here's a Small form contains 8-9 fields + a group of checkboxes
I want to save all details in DB + want to display in a table in proper manner, but it not works properly
Here's the code which i used
for($i=0;$i<count($_POST[wert1]);$i++)
{
if($_POST[wert1][$i]!= "")
{
$check1[] =$_POST['wert1'][$i]; } }
$new1=implode(',', $check1);
$result = "INSERT into table1(check1) values($new1)";
$result = mysqli_query($con, $result);
So i've one doubt that for each checkbox row, should i need to define same array name or different like here i used array name as wert1[] for first row
Checkbox values are not transmitted if the box is not checked.
If you have influence, you could put a hidden input field of the same name before the checkbox and the value "0", like:
<input type="hidden" name="checkbox_name" value="0" />
<input type="checkbox" name="checkbox_name" value="1">Some Text</input>
In you example site, you're using array notation, which is basically a good thing. However, you have not given an index so you might not recognize missing elements.

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

Dynamic forms and PHP

Ive started working on a dynamic form script that allows a user to add form elements via Jquery, which is then in turn submitted to a PHP script.
I'm just after some feedback on ways to achieve this. At the moment I have the following:
When a user adds a form element the element is added with the following name array:
<textarea name="element[text][123]">
<input type="text" name="element[input][456]" />
As I need to know the type of form element that was submitted I am using a multidimensional array called 'element[][]' where the first level of the array is the type of element and the second element of the array is a unique ID and the value.
When I var_dump() This after submission PHP outputs:
array
text => array
123 => string 'The textarea value'
input => array
456 => string 'The input field value'
Im working on the PHP side of the script now and just wondering if there is a better way to do this.
Any thoughts?
UPDATE
I have to change the way that Im doing this as the array keynames are not unique.
If the user adds two textareas
<textarea name="element[text][123]">
<textarea name="element[text][456]">
When the user adds a form element, the element can be dragged so the positioning can be changed after the element was created. This allows a user to add an element but then move it to where they want it to appear.
PHP handles this ordering fine and accepts the array in the order that the form is submitted, however as mentioned above if the key names are the same then the order will be broken.
On the PHP side I need to know
the type of form field
the value of the form field
the unique ID, which is just a timestamp, of the form field
I think I might need to do what Cole mentioned, assigning the names as:
element[text_123]
I can then explode the keyname on '_' to determine the type and the identifier.
UPDATE
I took the script Jack posted and slightly modified it
$vars = $_POST['element'];
foreach ($vars as $id => $vals)
{
// $vars[id] outputs the ID number
// $vars[vals] is the array containing the type and value
echo "This fields ID is $id. ";
foreach($vals as $key => $value)
{
echo "Type was: $key and the value was: $value <br />";
}
}
A quick test of this outputted
This fields ID is 1338261825063. Type was: heading and the value was: xzczxczxczxczxczxc
This fields ID is 1338261822312. Type was: heading and the value was: asdasdasdasdad
From this I know the identifier and the array that it belongs to, the type and the value, but I also know the order that the data was submitted.
From that I can wrap my data in markup, perform any additional operations and then insert the data into the database.
Looks okay; you could also consider something like this (it introduces more fields though, so you must really think the benefit is worth it):
<input type="hidden" name="element[123][type]" value="text" />
<input type="hidden" name="element[456][type]" value="input" />
<textarea name="element[123][value]">
<input type="text" name="element[456][value]" />
Then you can do this:
foreach ($_POST['element'] as $name => $info) {
// $info['type'] is 'text' or 'input'
// $info['value'] is the user input
}

is there a way to pass two values in an input checkbox to the $_POST

I have a bunch of checkboxes on the page and i want to pass two values for each checkbox like this....
<input name="class[]" value="first_value" data="second_value" type="checkbox" class="auto"/>
any idea how to get first_value and second_value past to the $_POST in php
any suggestions on how to do this
You can do this
<input name="class[]" value="CIS 2910C DL:3" type="checkbox" class="auto"/>
where you separate the two values by a : or whatever other separator you want.
Then on the $_POST you can use explode in a loop like this
$pieces = explode(":", $class);
echo $pieces[0]; // CIS 2910C DL
echo $pieces[1]; // 3
so you can pull out both values
You can't do it directly. I'd loop through with jquery and create new hidden inputs with those values and delete the data attr.
How about:
<input name="class[second_value][]" value="first_value" type="checkbox" class="auto"/>
Then in PHP
foreach($_POST['class'] as $first_value=>$tmpArray) {
foreach($tmpArray as $second_value) {
echo $first_value.": ".$second_value;
}
}
Odd way of doing it, but its seems like an odd situation you are in anyways.
I think you can only do this if you use ajax, or if you add a hidden field with an index sequential '[]' buying the checkbox with the value of X in X location hidden

Extract dynamically created form data

I've just started using jQuery. One thing I've been using it for is adding rows to a table that is part of a form.
When I add a new row, I give all the form elements names like 'name_' + rowNumber. I increment rowNumber each time I add a row.
I also usually have a Remove Row Button. Even when a row is removed, the rowNumber count stays the same to keep from repeating element names.
When the form is submitted, I set a hidden element to equal the rowNumber value from jQuery. Then in PHP, I count from 1 to the rowNumber value. Then for each value, I perform an isset($_REQUEST['name'_ . index]). This is how I extract the form elements that remained after deleting rows in jQuery.
Does anyone here have a better technique for accounting for deleted rows?
For some of our simpler tables, we use a field name such as 'name[]', though for JavaScript they would need a usable id.
It does add some complexity in that 'name[0]' has to assume 'detail[0]' is the correct element.
PHP will create an array and append elements if the field name ends with [] similar to
<input name="field[]" value="first value" />
<input name="field[]" value="second value" />
// is roughly the same as
$_POST['field'][] = 'first value';
$_POST['field'][] = 'second value';
Use arrays to hold you values in your submission. So bin the row count at the client side, and name your new elements like name[]. This means that $_POST['name'] will be an array.
That way at the server side you can easily get the row count (if you need it) with:
$rowcount = count($_POST['name']);
...and you can loop through the rows at the server side like this:
for ($i = 0; isset($_POST['name'][$i]; $i++) {}
You could extract all the rows by doing a foreach($_POST as $key => $value).
When adding a dynamic form element use the array naming method. for example
<input type="text" name="textfield[]" />
When the form is posted the textfield[] will be a PHP array, you can use it easily then.
When you remove an element make sure its removed from the HTML DOM.
Like blejzz suggests, I think if you use $_GET, then you can just cycle through all of the inputs that were sent, ignoring the deleted rows.
foreach ($_GET as $k=>$v) {
echo "KEY: ".$k."; VALUE: ".$v."<BR>";
}
I notice that you mention "accounting for deleted rows"; you could include a hidden input, and add a unique value to it each time someone deletes a row. For example, the input could hold comma-separated values of the row numbers:
<input type="hidden" value="3,5,8" id="deletions" />
and include in your jQuery script:
$('.delete').click(function(){
var num = //whatever your method for getting the row number
var v = $('#deletions').val();
v = v.split(',');
v.push(num);
v = v.join(',');
$('#deletions').val(v);
});
Then you should be able to know which rows were deleted (if that is what you were looking for).
you can use POST or GET
After submit you can use all of your form element with this automaticly. You dont need to reorganise your form element names. Even you dont need to know form elements names.
<form method="POST" id="fr" name="fr">.....</form>
<?php
if(isset($_POST['fr'])){
foreach($_POST as $data){
echo $data;
}
}
?>
Also you should look this
grafanimasyon.blogspot.com.tr/2015/02/veritabanndan-php-form-olusturucu.html
This is a automated form creator calcutating your database tables. You can see how to give name to form elements and use them.

Categories