I have fieldset with multiple checkboxes for a MySQL insert from a form.
<fieldset id="my_checkboxes">
<legend>My Checkboxes (Select at least 2)</legend>
<label for="checkbox1">
<input type="checkbox" id="checkbox1" value="yes" name="the_checkbox" />
CheckBox #1
</label>
<label for="checkbox2">
<input type="checkbox" id="checkbox2" value="yes" name="the_checkbox2" />
CheckBox #2
</label>
</fieldset>
I need to be able to have each checkbox have a unique NAME attribute because each checkbox inserts data into it's own column in the database. (Otherwise, i would just use the the_checkbox[] as the name for each).
My problem is I need to have the user select at least 2 checkboxes in order to submit the form. Since I have seperate names for each, I cannot use the following code anymore as it counts by name:
$checkboxcount = count($_POST['the_checkbox']);
if($checkboxcount < 1)
{
$errors[] = $checkboxcount;
}
MY SQL statement looks like this:
$sql = "INSERT INTO $db_table(the_checkbox,the_checkbox2) values
(
'".mysql_real_escape_string(stripslashes($_REQUEST['the_checkbox']))."',
'".mysql_real_escape_string(stripslashes($_REQUEST['the_checkbox2']))."'
)";
What would you suggest for me to either A. Count checkboxes even with seperate Names, or B. keep the same name but somehow insert data into MySQL as seperate column names?
If you prefer to keep different names, then do something like this:
$chkbox_count = 0;
if (isset($_POST['the_checkbox']) && $_POST['the_checkbox'] == "yes") $chkbox_count++;
if (isset($_POST['the_checkbox2']) && $_POST['the_checkbox'] == "yes") $chkbox_count++;
// etc...
I would usually prefer to use use the same name for a related group of checkboxes though, with different values, but the way you are handing them directly into a SQL string makes your method of different names a little easier to handle.
Related
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.
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 />";
}
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);
}
}
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);
}
}
In Php as we all know, there are no inbuilt controls by itself like Asp.Net's GridView etc. I am using Html's <table> to build up the grid and keep the row's id in one hidden field. I've also placed one checkbox at the beginning of each row and a delete button at the bottom of the grid. The problem i face is, how do i get all the id's that are checked so that i can pass those ids in my IN clause of Delete?
Take a look at what is currently being submitted:
var_dump($_POST);
You will see all of the field values. If you do the checkboxes right, you'll have an array of rowID's to delete, and you can simply implode(',',$_POST['checkBoxes']) or something similar when building your query.
Security would be a concern here... I'm sure someone else will post in depth about that, but you definitely want to validate that the user can delete these records.
Name every checkbox with a semi-unique name like tablerow[numeric_id]. When you submit the form you can simply catch all posted tablerow value that was checked.
First you name all your checkboxes by suffixing [] in their name so that an array gets created, later this is how you can get those that are checked and act accordingly:
for($i = 0; $i < count($_POST['checks']); $i++)
{
if (isset($_POST['checks'][$i]))
{
// this was checked !!
}
}
Where checks is the name of all those checkboxes eg:
<input type="checkbox" name="checks[]" value="1" />
<input type="checkbox" name="checks[]" value="2" />
<input type="checkbox" name="checks[]" value="3" />
And this is how you can get those for your IN clause in your query:
$checked_array = array();
for($i = 0; $i < count($_POST['checks']); $i++)
{
if (isset($_POST['checks'][$i]))
{
$checked_array[] = mysql_real_escape_string($_POST['checks'][$i]);
}
}
// build comma separated string out of the array
$values = implode(',', $checked_array);
Now you can use the $values in your IN clause of your query.