1

I'm having a problem with storing and updating checkboxes values. When I select/unselect them all it works, but when I select the last one the value is set to the first unchecked box and so on.

HTML Form:

echo'<input type="hidden" name="numOfRows" value="'.mysql_num_rows($query).'">';

if ($row[10]==1)
 {
  echo'<input type="checkbox" id="activateExam" name="activateExam[]" value="1" checked="checked">';
 }
else if ($row[10]==0)
 {
  echo'<input type="checkbox"  id="activateExam"  name="activateExam[]" value="0" >';
 }
echo'<input type="hidden" name="id[]" value="'.$row[0].'">';

PHP code:

for ($i = 0; $i < $_POST['numOfRows']; $i++)
{
if (isset($_POST['activateExam'][$i]))
{
    $activateExam = '1';
}
else
if (!isset($_POST['activateExam'][$i]))
{
    $activateExam = '0';
}

$id = $_POST['id'][$i];
echo "exam" . $activateExam . " id: " . $id;
$sql = "UPDATE `student` SET `activateExam`='" . $activateExam . "' WHERE `ID`='" . $id . "'";
$query = mysql_query($sql);
if (!$query) echo "Database Error : " . $sql;
}

Hope you can help, thanks anyways.

3
  • where is $_POST['numOfRows']? Commented Dec 10, 2013 at 11:05
  • Sorry I forgot to copy it, it's there now. Commented Dec 10, 2013 at 11:10
  • try the given way in answer. i think you want to active them which are selected and inactive others. Commented Dec 10, 2013 at 11:12

1 Answer 1

2

try it

HTML

if ($row[10]==1)
 {
  echo'<input type="checkbox" id="activateExam" name="activateExam[]" value="'.$row[0].'" checked="checked">';
 }
else if ($row[10]==0)
 {
  echo'<input type="checkbox"  id="activateExam"  name="activateExam[]" value="'.$row[0].'" >';
 }

and php

mysql_query("UPDATE `student` SET `activateExam`=0 ") or die(mysql_error()); // update all to 0

if(isset($_POST['activateExam']))
{
   $arr_active_exam = $_POST['activateExam'];
   if(sizeof($arr_active_exam)>0)
   {
      foreach($arr_active_exam as $id)
      {
          mysql_query("UPDATE `student` SET `activateExam`=1  WHERE id='$id' ") or die(mysql_error()); // update all to 1 which is checked 
      }
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

you can use limit 1 if your id column is primary key. as WHERE id='$id' LIMIT 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.