If checked value 1 else 0

I have multiple checkboxs that i need to insert in to db. If the checkbox is checked I want to insert 1 else 0.
Im pretty sure I could do it like this


<input type="checkbox" name="am" value="1" /> A.M.


$checkbox1 =  if(isset($_POST['am'])) {
echo "1"; }
else
echo "0";

But i have like 30 checkboxs i am dealing with and might add more later on. And not wanting to do the above 30 plus time any way to make it check all checkboxs at once. Still slowly learning php code above may not even work but im pretty sure something like that would work.

if you want to store the values in a database, and you control the front-end of the form just save them into a array like so $checkbox = array($_POST[‘am’], $_POST[2]) and so on for each field, if the check box was not checked than it will not return 1 so then just cycle through the variables in a for loop checking if they are set to 1 or not, if not simply set them equal to 0 and then upload them all to a database.

Hope that helps

Thanks Max. Im sure its easy enough just not wrapping my head around that. Something like this?
I found this example on another site not sure how I would end up using it.


foreach (array('checkbox1', 'checkbox2', 'checkbox3') as $k) {
    if (!isset($_POST[$k])) {
        $_POST[$k] = '0';
    }
}

I also found this way that might solve it using a hidden field


 <input type="hidden" name="my_checkbox_1" value="0" />
    <input type="checkbox" name="my_checkbox_1" /><label>One</label>
    <input type="hidden" name="my_checkbox_2" value="0" />
    <input type="checkbox" name="my_checkbox_2" /><label>Two</label>
    <input type="hidden" name="my_checkbox_3" value="0" />
    <input type="checkbox" name="my_checkbox_3" /><label>Three</label>

the above way is exactly what i was thinking, except that i would probably do something along these lines:


$checkbox = array($_POST[cbox1], $_POST[cbox2], $_POST[cbox3], $_POST[cbox4]); //and so on
for($i = 0; $i < count($checkbox); $i++){
if($checkbox[$i] != 1)
{
$checkbox[$i] = 0;
} //end if
} //end for
//database stuff here

I’m not sure about the other way that you showed, but another way is to just use JavaScript to change checkboxs that are selected to 1, but i wouldn’t recommend that as a user might have JavaScript off…

Off Topic:

Even though it “works” please don’t use this

Since PHP will first look if there is a constant with the name cbox1 and use it’s value if it does, and only if it doesn’t exist will it use the text ‘cbox1’ as a string (and throw the notice PHP Notice: Use of undefined constant cbox1 - assumed 'cbox1'. Which is bad enough, but things get worse if you ever decide to actually introduce cbox1 as a constant … Instead just use $_POST[‘cbox1’], $_POST[‘cbox2’], etc.

Ok so after i get this set up


$checkbox = array($_POST[cbox1], $_POST[cbox2], $_POST[cbox3], $_POST[cbox4]); //and so on
for($i = 0; $i < count($checkbox); $i++){
if($checkbox[$i] != 1)
{
$checkbox[$i] = 0;
} //end if
} //end for
//database stuff here
$insert = "INSERT INTO tags (id, am, am2, am3 and so on)

  VALUES ('".$id."', ')"; // what would the value be $_POST[''] or $checkbox?

$add_member = mysql_query($insert);

what then would i insert as values? still $_POST[‘check1’] or would it be $checkbox for each value?

no you could just do $checkbox[1], $checkbox[3], $checkbox[3]… and so on since you know which ones correspond to what values, oh and ScallioXTX is right you need to include the quotations, i was just rushing so i missed them so it should be $_POST[‘cbox1’] instead of $_POST[cbox1], quite embarrassing…

What you need to do is like this:

  1. I suppose you are getting the list of students from database, right ?
  2. You need to set all students present as 1 and absent as 0 and add to your previous attendance database… ok… !
    So, here starting with the HTML & PHP Display code (the one which will be displayed) first:

<form method="post">
<table width="100%" border="1">
<tr align="center">
<th>Roll no</th><th>Name</th><th>Select</th>
</tr>
<?php
$q1 = mysql_query("select query from table for fetching all students list.");
$i=1; //define a variable which we will keep incrementing throughout while loop, to name all our checkboxes..
while($q2 = mysql_fetch_array($q1))
{
?>
<tr align="center">
<td><?php echo $q2['rollno']; ?></td>
<td><?php echo $q2['sname']; ?></td>
<td><?php echo $i; ?><input type="checkbox" checked="checked" name="chk<?php echo $i; ?>" /></td>
</tr>
<?php
$i=$i+1;
}
?>
<tr>
<td colspan="3" align="right">
<input type="hidden" value="<?php echo $sub; //store subject ?>" name="attendsubject" />
<input type="hidden" value="<?php echo $cl1; //store class ?>" name="attendclass" />
<input type="submit" value="Submit Attendance" name="submitattend" /></td>
</tr>
</table>
</form>


Now, since we have displayed the form, let’s submit the attendance back to the database…
Here is the code for it, which I used successfully, you may further do the changes as you wish, after understanding the logic…



if(isset($_POST['submitattend']))
{
set_time_limit(0);
$_SESSION['subject'] = $_POST['attendsubject'];
$_SESSION['branch']=$_POST['attendclass'];
$sub1 = $_SESSION['subject'];
$class1 = $_SESSION['bra'];
    $q3 = mysql_query("Select * from `class` ORDER BY `rollno` ASC"); // get all roll numbers
    $count = mysql_num_rows($q3);
    $j = 1;
    while($q4 = mysql_fetch_array($q3))
    {
        //store roll number in variable while running the while loop
        // now run a query to fetch the old attendance of student and store it in variable.. I used $q7 here for storing array results here.. 
        if(isset($_POST['chk'.$j]))
            {
                
                $v2 = $q7['finalattend']+1; //total attendance of student
                $v3 = $q7['totalattend']+1; //total attendance taken by teacher
                mysql_query("UPDATE `attend` SET `finalattend`='".$v2."', `totalattend`='".$v3."' where `attenduser`='".$v1."' and `attendsub`='".$sub1."'") or die(mysql_error());
            }
            else
            {
                $v2=$q7['totalattend']+1;
                mysql_query("UPDATE `attend` SET `totalattend`='".$v2."' where `attenduser`='".$v1."' and `attendsub`='".$sub1."'") or die(mysql_error());
        
        }
        
    
    $j=$j+1;
    }
    header("Location: logout.php"); //logout after taking attendance.. 
}


Here it ends… I made this post in a hurry, so sorry for the usage of my variable types, i couldn’t think of some other thing at that time, but i hope, i would have helped you a bit… if there is a problem, let me know, will show you whole page…
actually i made it for college, so there are various options to be included like branch, class and year… that’s why i posted excerpts here… hope you don’t mind that :smiley:

One more thing, I also took all check box as checked by default, it’s easy to deselect 4 check box then selecting 100 :smiley: :wink:

Thanks for all the help the problem im still running in to is on my page that validates and inserts it is still saying that the variable is unknown. Is this


$checkbox = array($_POST[cbox1], $_POST[cbox2], $_POST[cbox3], $_POST[cbox4]); //and so on
for($i = 0; $i < count($checkbox); $i++){
if($checkbox[$i] != 1)
{
$checkbox[$i] = 0;
} //end if
} //end for
//database stuff here
$insert = "INSERT INTO tags (id, am, am2, am3 and so on)

  VALUES ('".$id."', ')"; // what would the value be $_POST[''] or $checkbox?

$add_member = mysql_query($insert);  

supposed to be on the page that the form is on? When it gives a list of all unknown variables the checkbox’s that were checked are not on the list. So what im lost on and not understanding is how do i make sure that even the checkbox’s that are not selected send a value?

Change that code to


$checkbox = array($_POST['cbox1'], $_POST['cbox2'], $_POST['cbox3'], $_POST['cbox4']); //and so on

and see if that works.

Thanks Max still nothing. Data is being inserted in to the other three tables but nothing in the tags table. Still getting Undefined index for all unchecked checkboxes.

i think im working on the wrong page dont i need to have the $checkbox = array( ) on the page with the form? to make sure the variables are sent checked or not checked?

Did you make sure to use the correct $checkbox[I] number, in the insert command, also make sure that all the names are correct, when retrieving the values, if that still doesn’t work try doing print_r on the array to see what values are coming up.

Oh and no, the code above will collect all the values that the POST sends,if its not checked POST will not send. Anything so when you check it against 1 the garbage value it holds will be set to 0.

What you need is just this and it will solve your problem…


<html>
<head>
</head>

<body>
<form method="POST">
<?php
$i = 1; // define starting variable
while($i <= Number you want)
{
?>
<input type="checkbox" checked="checked" name="checkbox<?php echo $i; ?>" /> <br />
<?php
}
?>
<input type="submit" name="submitchkbx" />
</form>
</body>
</html>

Now the PHP code to run it.


<?php
if(isset$_POST['submitchkbx'])
{
    for($j=1; $j <= the same number for $i; $j++)
    {
         if(isset($_POST['checkbox'.$j]))
         {
              Perform action you want // store 1 for selected checkbox
         }
         else
         {
             Else perform this action // you also set a column in your database for storing 0 or 1.. store 0 for unselected checkbox
         }
    }
}
?>

I hope this solves the problem… no need to define complex arrays

If you do this your probably going to end up preforming a sql query multiple times, which will take much more memory than required, its much easier to just define and populate the array using the post data and then just input each value of the array into the sql query like this:


$sql = "INSERT INTO Tags (a, b, c, d) VALUES ($checkbox[1], $checkbox[2], $checkbox[3], $checkbox[4])";

If you have that many checkboxes to cycle through, why not put them in an form name array:


<?php

	if( isset($_POST['cbox']) ) {
		$columns = array();
		$values = array();
	
		foreach( $_POST['cbox'] as $k => $v ) {
			$columns[] = $k;
			$values[] = 1;
		}
		echo 'INSERT INTO table (' .implode(',', $columns). ') VALUES (' .implode(',', $values). ')';	
#  Example:   INSERT INTO table (box_9,box_10,box_30) VALUES (1,1,1)
	}
	
?>
<!DOCTYPE html>
<html>
	<body>
		<form method="post" action="test3.php">
			<input name="cbox[box_1]" type="checkbox"><label>Box 1</label>
			<input name="cbox[box_2]" type="checkbox"><label>Box 2</label>
			<input name="cbox[box_3]" type="checkbox"><label>Box 3</label>
			<input name="cbox[box_4]" type="checkbox"><label>Box 4</label>
			<input name="cbox[box_5]" type="checkbox"><label>Box 5</label>
			<input name="cbox[box_6]" type="checkbox"><label>Box 6</label>
			<input name="cbox[box_7]" type="checkbox"><label>Box 7</label>
			<input name="cbox[box_8]" type="checkbox"><label>Box 8</label>
			<input name="cbox[box_9]" type="checkbox"><label>Box 9</label>
			<input name="cbox[box_10]" type="checkbox"><label>Box 10</label>
			<input name="cbox[box_11]" type="checkbox"><label>Box 11</label>
			<input name="cbox[box_12]" type="checkbox"><label>Box 12</label>
			<input name="cbox[box_13]" type="checkbox"><label>Box 13</label>
			<input name="cbox[box_14]" type="checkbox"><label>Box 14</label>
			<input name="cbox[box_15]" type="checkbox"><label>Box 15</label>
			<input name="cbox[box_16]" type="checkbox"><label>Box 16</label>
			<input name="cbox[box_17]" type="checkbox"><label>Box 17</label>
			<input name="cbox[box_18]" type="checkbox"><label>Box 18</label>
			<input name="cbox[box_19]" type="checkbox"><label>Box 19</label>
			<input name="cbox[box_20]" type="checkbox"><label>Box 20</label>
			<input name="cbox[box_21]" type="checkbox"><label>Box 21</label>
			<input name="cbox[box_22]" type="checkbox"><label>Box 22</label>
			<input name="cbox[box_23]" type="checkbox"><label>Box 23</label>
			<input name="cbox[box_24]" type="checkbox"><label>Box 24</label>
			<input name="cbox[box_25]" type="checkbox"><label>Box 25</label>
			<input name="cbox[box_26]" type="checkbox"><label>Box 26</label>
			<input name="cbox[box_27]" type="checkbox"><label>Box 27</label>
			<input name="cbox[box_28]" type="checkbox"><label>Box 28</label>
			<input name="cbox[box_29]" type="checkbox"><label>Box 29</label>
			<input name="cbox[box_30]" type="checkbox"><label>Box 30</label>
			<input type="submit" name="submit" />
		</form>
	</body>
</html>

You are wrong in this concept my dear… when the query is run, the results are stored in an array, as you can see above… it’s not a very big loop, I made a project to take attendance of 1600 students of college using this and it worked fine… no delay …

hi aprexd i would like to say thank you to you if you show your email or send me the code of attendence system means which can take value and either absent or present but complete code i want to insert it in my project no one helping me please and i am new here its a request please here is my email
batkhelak@gmail.com