I've tried to get those checkbox that are unchecked. At this moment i'm just getting those that are checked. Here is my code. That value will be inserted on a table which i don't want to leave it null, that's why i need to get those checkbox unchecked, so that i could insert 1 for checked or 0 for unchecked:
<?php
if (!empty($_POST['menu'])) {
# code...
foreach ($_POST['menu'] as $value) {
# code...
echo "<p>ID Checkbox checked: ".$value;
}
}
?>
One of the reasons for what i need to get both status: checked or unchecked is because i don't want to leave database fields empty.
Unchecked checkboxes don't get POSTed. If you know what fields should be there, you'll probably have to list them out manually.
The wonderful thing about checkboxes is that when you don't have one checked, and you submit a form, nothing is sent to the server. Take this checkbox for example:
<input type="checkbox" name="test"/>
If you left it unchecked and looked for $_POST['test'] it would error out, as it is not set.
So, try doing this:
if(!isset($_POST['name_of_checkbox'])){
// Fill database with some empty value.
} else {
// Do what you need to do for checked value.
}
Hope that gives you some insight!
Say if they are named the same, and you know the number of checkbox you can use a for loop:
if (!empty($_POST['menu'])) {
for ($i=0; $i < 10; $i++) {
if(isset($_POST['menu'][$i])){
echo "Checkbox checked: " . $_POST['menu'][$i];
}else{
echo "Checbox uncheck #" . $i;
}
}
}
You can put the names in an array, then iterate:
$checkboxes = array('cbx1', 'cbx2', 'cbx3');
foreach ($checkboxes as $checkbox) {
if (isset($_POST[$checkbox])) {
echo "<p>ID Checkbox checked: " . $_POST[$checkbox];
} else {
echo "Checbox uncheck :" . $checkbox;
}
}
So yeah many ways to achieve this, it depends on the situation.
Check for #Artur approach as well for client side solution.
<input type="hidden" name="checkbox[8]" value="0">
<input type="checkbox" name="checkbox[8]" value="8">
This would be one way to also get 0's posted. Important part is that the name's are the same. So if checkbox is checked, it's value would override the hidden input value.
Thank you all for your time and be so kind to answer my question. The reason for what i needed to have those checkboxes unchecked and checked is because i have a dynamic menu and so i assign menus to users. Here is the solution i found with a friend of mine at work:
Code for the checkboxes. I query all the menus available on my table Menus so that i will show the administrator all the menus availables so then he could choose which menus he will assign to the users:
´
<table>
<tr>
<td>Menus a asignar:</td>
<td>
<?php
$query_menus_checkbox = mysql_query("SELECT id_menu, nombre_menu FROM menus");
while ($checkbox_mostrar = mysql_fetch_row($query_menus_checkbox)) {
# code...
?>
<input type="checkbox" name="menus[<?php echo $checkbox_mostrar[0]; ?>]" value="<?php echo $checkbox_mostrar[0] ?>"><?php echo $checkbox_mostrar[1] ?>
<p></p>
<?php
}
?>
</td>
</tr>
</table>
´
Then here is the code to process which checkboxes are checked or not to insert on my table (id_user is not shown but i have taken from another query which is not shown so you'll have to query yourself):
´
$res=mysql_query("select id_menu from menus");
$arid=array();
while($xd=mysql_fetch_assoc($res)){
$arid[]=$xd['id_menu'];
}
for($i=0;$i<count($arid);$i++){
$id_menu=$arid[$i];
$activo=(isset($_POST['menus'][$id_menu]) && $_POST['menus'][$id_menu]!="")?1:0;
$inserta_menus = mysql_query("INSERT INTO menus_usuarios(id_menu, id_usuario, estado) values ('$id_menu', '$id_user[0]', '$activo')");
}
´
Related
So, my webpage has a html-table which displays rows with one item pr. row including various data regarding that item in the columns.
The table is populated using mysqli call to db. So far so good.
Excerpts of the table look like this (I've tried to only show the "important" parts of the code to avoid cluttering - there 8 more text fields similar to "nytAntalGangeUdfoert" for each item)
<td><input type="text" name="nytAntalGangeUdfoert[]" value="<?php echo $antalGangeUdfoert ?>"></td>
<?php if ($aktivStatus == 1) { ?>
<td><input type="checkbox" name="nyAktivStatus[]" value="<?php echo $aktivStatus ?>" checked="checked"/></td>
<?php } else { ?>
<td><input type="checkbox" name="nyAktivStatus[]" value="<?php echo $aktivStatus ?>" /></td>
The text field(s) works fine in all aspects.
For the checkbox, the if-else part decides whether the checkbox should be displayed as checked (active or not) dependent on the value in my db-table (1 or 0) This works fine.
I then have 'duplicate' hidden fields to log the original status of the checkbox for later comparison after posting:
<td><input type="hidden" name="antalGangeUdfoert[]" value="<?php echo $antalGangeUdfoert ?>"></td>
<td><input type="hidden" name="aktivStatus[]" value="<?php echo $aktivStatus ?>"></td>
All of this is posted to another page where it is handled as follows (again, only excerpts of the full table). 'aktivstatus' is the old status from db, and 'nyaktivstatus' is the one posted (i.e. the one selected by the user via the checkboxes - can of course be the same as original state)
if(isset($_POST['submit']))
{
$antalGangeUdfoert = $_POST["antalGangeUdfoert"];
$nytAntalGangeUdfoert = $_POST["nytAntalGangeUdfoert"];
$aktivStatus = $_POST["aktivStatus"];
foreach( $navn as $n => $n )
{
if(isset($_POST["nyAktivStatus"][$n])) {
$nyAktivStatus[$n] = 1;
} else {
$nyAktivStatus[$n] = 0;
}
if( $antalGangeUdfoert[$n] <> $nytantalGangeUdfoert[$n] || $aktivStatus[$n] <> $nyAktivStatus[$n]) {
//run function to update items where a change has been made by the user)
As stated earlier, the above approach works fine for all the text fields, but in some cases, the new state of a checkbox is saved for the wrong item, apparently (changes to the text fields are correctly saved in db regardless)
Examples below:
Row---status when fetched---user input---saved as
Row1: 1-->0-->1 ERROR
Row2: 1-->1-->1 OK
Row3: 1-->1-->0 ERROR
Row1: 1-->1-->1 OK
Row2: 1-->1-->1 OK
Row3: 0-->1-->1 OK
Row1: 1-->0-->0 OK
Row2: 1-->0-->0 OK
Row3: 1-->0-->0 OK
Row1: 0-->1-->1 OK
Row2: 0-->1-->1 OK
Row3: 0-->1-->1 OK
Row1: 1-->0-->1 ERROR
Row2: 1-->0-->0 OK
Row3: 1-->1-->0 ERROR
FYI at one point, I changed the checkbox into a textfield and manually entered 1 or 0, and this worked fine...not ideal solution, though...
So, I guess there's something going wrong when posting/assigning the "nyaktivstatus' (user entered status)
Can anyone spot the issue in my code? Or spot a pattern that I'm not seeing?
Thanks!
$aktivStatus may not be set at all if the checkbox was not ticked.
Right where you have $aktivStatus = $_POST["aktivStatus"]; try replacing it with:
if (!array_key_exists('aktivStatus',$_POST))
$aktivStatus = 0;
else
$aktivStatus = $_POST["aktivStatus"];
This way if the checkbox was not set and the browser did not POST it at all, your variable will assume 0, otherwise it'll assume the value POSTed by browser.
As the unchecked checkboxes are not carried on post,in this case we might use a little javascript to take the value of checkboxes to a corresponding hidden text box on the on change event of the checkbox. here's a sample javascript to keep on the same page as my form below. This code is a demonstration on how to achieve the questioners target. Could be possible other ways to achieve this. Sessions could also be used on some parts.
<script type="text/javascript">
function changed(id){
var checkBoxValue=document.getElementById(id).value;
id=id.replace('checkbox','');
hTextBoxid='hidden['+id+']';
var hiddenTextBox=document.getElementById(hTextBoxid);
hiddenTextBox.value=checkBoxValue;
}
</script>
Here's the form
<?php
//uncomment for debugging
//if(isset($_POST)){
//for debugging could use this to see the variables that were passed on form submit
//echo '<pre>'; print_r($_POST); echo'</pre>';
//on post of data remember to sanitize and do the checks here server side.
//as we used javascript on the form for checkboxes and hidden text box should varify those post data on server side here.for example whether the check box array count and value matches..
//;}
?>
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<table>
<tr>
<?php
//sample data as if it came from db
$antalGangeUdfoert=array('a','b','c','d','x','y','z');
//sample data as if it came from db
$aktivStatus=array(0,0,1,0,1,1,0);
?>
<?php
$i=0;
//could use a for loop after counting the fetched rows,
//could use other than $aktivStatus, i used $aktivStatus here
foreach($aktivStatus as $aktivStatus){
echo '<td><input type="text" name="nytAntalGangeUdfoert['.$i.']" value="'.$antalGangeUdfoert[$i].'"></td><td>';
//check whether its checked depending on activeStatus
$aktivStatus[$i] == 1? $check='1':$check="0";
//and according to check draw a check box and a hidden text for each
echo '<input type="hidden" id="hidden['.$i.']" name="nyAktivStatus['.$i.']" value="'.$check.'"/>
<input type="checkbox" id="checkbox'.$i.'" value="'.$aktivStatus[$i].'" checked="'.$check.'" onChange="changed(this.id);"/>';
$i++;
};
?>
</td></tr></table>
<input type="submit" name="sub" value="sub"/>
</form>
I am building a site with a number of independant check boxes that collect information about industry topics. I user will check the ones of interest and store “Yes” in the database which is Filemaker.
When they return, they will see the ones previously checked and can uncheck if needed.
To this end, I am trying to get a check box to display as checked if the database value is equal to “Yes” and display as unchecked if the value is blank. Also, of the user checks the checkbox on the form, it will send the value of “Yes” back to the database and a value of blank if the check box is unchecked.
So far, I am only able to display the “Yes” or blank for fields. Here is my code so far:
<input type="text" name="Core_Compentencies__Marketing" value="<?php echo $port_row->getField('Core_Compentencies::Marketing'); ?>"></td>
Any help is appreciated.
Thanks.
usually i use helper function to decide whether field value is checked or not.
<?php
function isChecked($value = '', $defaultVal = 'Yes')
{
if($value == $defaultVal)
{
return 'checked';
}
}
?>
<input name="checkbox" type="checkbox" value="Yes" <?php echo isChecked(Core_Compentencies::Marketing); ?>>
This gives lists all people in the db and give a drop down for each one of them i want to make it so when i hit one submit button it enters individual values for each person.
so if you make yes for bobby no for mark and yes for dustin you can the pres submit and it will enter that for there values
$results = mysql_query("SELECT * FROM `$tabeluser` WHERE buss='$buss' ORDER BY id DESC LIMIT 1");
while($rows = mysql_fetch_array($results) )
{
fn = $_POST['firstname'];
echo $fn;
?>
<form>
<select name="check">
<option>no</option>
<option>yes</option>
</select>
<?php
<input type="submit" name="submit">
?>
<form>
<?php
}
mysql_query("INSERT INTO `$fn` (buss) VALUES ('$_POST[check]')");
First of all, you create a <form> and a submit button for each of the records you have. That is wrong, since you want to update multiple values at once.
What it should look like would be:
<form>
<?php
while($rows = mysql_fetch_array($results)) {
print '<select name="check[]"> .. </select>';
}
?>
<input type="submit" name="submit" />
</form>
Secondly, your code is formatted as if you are expecting to get $_POST[check] right after sending the code to the browser. That is not how PHP works. You need to separate the logic of having posted values, before printing the actual page contents. PHP is server side, which means that it won't get any data, unless the script is called with it from the beginning. So, that should look something like:
<?php
if (isset($_POST["check"])) {
// handle posted data.
}
else {
// show form
}
// or show form here, without an else, if you want to always show a form,
// even when you have posted values.
?>
Last but not least, you need to find a way to know which posted value belongs to each of your records. The way you have it now (<select name="check">') it will just return you one single value.
If you write it the way I intentionally did above (`) you will get all values, but still you won't be able to easily recognize which value is for each record.
Instead, you may want to do a final result of something like:
<?php
// get mysql records into an array (say $my_array)
if (isset($_POST["submit"])) {
foreach($my_array as $record) {
if (isset($_POST["select_of_id_".$record["id"])) {
// insert additional value into db
}
}
}
print '<form>';
foreach($my_array as $record) {
print '<select name="select_of_id_'.$record["id"].'">';
print '<option value="0">no</option><option value="1">yes</option>';
print '</select>';
}
print '<input type="submit" name="submit"/>';
print '</form>';
?>
Changes required in your code :-
<select name="check[]">
<option value="<?php echo $userId;?>_0">no</option>
<option value="<?php echo $userId;?>_1">yes</option>
</select>
You should make changes in you DB It help to easy maintaing your data.
Create new table where you can save multiple user check data with respective Post
for e.g post_id user_id check
101 111 0
101 112 1
How you can store data from you html
In you post array you will get check array in which you will get multiple check value like this
101_0 if no selected and 102_1 if yes selected. Now you need to explode this value.
$_POST['check'] = array(0 => `101_0`, 1 => 102_1);
Inside loop you can extract userid and respective checked value.
for e.g
$checked = explode('_','101_0');
$userId = $checked[0];
$check = $checked[1];
I have created a table of checkboxes. The rows are divided up by category, and either a checked or unchecked checkbox gets displayed under a department column. I have a lot of code so I will break down what I am supplying. I am creating an array via each column (odd method, yes). I have noticed that if all check boxes are deselected, it will return the hidden value of 0 each time it loops. Thats great, thats what I wanted. However, if the box is selected, it returns both the value of 0 and the value of 3. For instance:
Test = Array()
Test[0] => 0
Test[1] => 3
How can I prevent it from posting the hidden value?
$row_two = mysql_query("SELECT dept_id FROM categories WHERE cat_name = '{$cats['cat_name']}' and bus_id = '{$busUnits['bus_id']}'");
while (($test_two=mysql_fetch_assoc($row_two)))
{
$AnotherTest = implode(',', $test_two);
$WhatTest = explode(",", $AnotherTest);
if(in_array("3",$WhatTest, TRUE))
{
echo '<input type="hidden" name="Cat_CBC_Test_One[]" value="0">';
echo '<td><input type="checkbox" name="Cat_CBC_Test_One[]" value="3" checked></td>';
}
else
{
echo '<input type="hidden" name="Cat_CBC_Test_One[]" value="0">';
echo '<td><input type="checkbox" name="Cat_CBC_Test_One[]" value="3"></td>';
}
To detect unchecked Checkboxes i would add a hidden field with a different name, like _Cat_CBC_Test_One. That way you dont have the issue with the hidden field interfering.
Then, on the server, you scan through for parameters that start with _ and add the missing "false" Parameters for further processing.
I am currently trying to design a for loop to iterate through any 'checked' check boxes, and from that, use the value within the 'value' slot to run some queries. I am unfortunately struggling with this as the list of checkboxes are not pre-defined, they are dynamic from the database pending the users previous selection.
The loop actually works to present the items to be checked:
?>
<input type="checkbox" name="option[]" value="$listing_id">
<font size="+1" color="green"><?php echo"$list_name"; ?>:</font><br />
<?php
The listing ID within the value is what I need to work with in a mysql query before I run an update query. The for loop that's meant to work is:
foreach($_POST['option'] as $option) //loop through the checkboxes
{
...
}
The update query will work within this as its simply copied from somewhere else, I just need the 'Listing_ID' from the check boxes that are checked.
I ran this code to hopefully do some debugging:
if(empty($_POST['option'])){
echo "no checkboxes checked.";
} else {
if(!isset($_POST['option'])){
echo "no set.";
}
}
and it returns "no checkboxes checked."
I have now hit a grey area as to why this for loop isn't working (this was taken from another example on the internet).
empty($_POST['option']) will return true, if either $_POST['option'] is not set (same as !isset($_POST['option']) (!)) or an empty array.
If you need to debug what's going on, use var_dump($_POST['option']); to find out what has been submitted for the option checkboxes. I also suggest you do a var_dump($_POST); so you can see what has been submitted overall - e.g. in case the post action is not post you will immediatly notice). For HTML output:
echo '<pre>', htmlspecialchars(print_r($_POST, true)), '</pre>';
That should give you the information you're looking for. For each individual checkbox, you can do:
foreach($_POST['option'] as $option) //loop through the checkboxes
{
var_dump($option);
}
First of all your code seems to be bugged to me. Maybe is just a typo but
<input type="checkbox" name="option[]" value="$listing_id">
should be
<input type="checkbox" name="option[]" value="<?=$listing_id?>"/>
Moreover using empty over an array is not good at all.
Try echoing out the $option in the loop to see what the value is and there you can see if there is something there.
foreach($_POST['option'] as $option) //loop through the checkboxes
{
echo $option . "<br />";
}
Also make sure your form's method is set to POST or that it's action is pointed to the correct place. You also have an error in your input:
<input type="checkbox" name="option[]" value="$listing_id">
I assume you meant:
<input type="checkbox" name="option[]" value="<?php echo $listing_id;?>">
UPDATE:
The error ended up not being in the code posted. Error was discovered in an if statement that always returned false that in-cased the code posted above.