Update Checkbox Value Using PHP & MySQL
This code will send exactly two query’s to update a INT (0 or 1) checkbox field in a MySQL database.
The IN operational statement let’s you match on a list of values in a clause. The implode statement will turn the array (shown below) into a string.
| PHP | | copy code | | ? |
| 01 | |
| 02 | <?php |
| 03 | if (isset($_POST['doSave'])){ |
| 04 | if (isset($_POST['checkbox'])){ |
| 05 | $doSave = implode(',',$_POST['checkbox']); |
| 06 | //if checkbox IS checked, update the database with a value of 1 |
| 07 | $updatequery = "update databasename set checkbox='1' where id IN ($doSave)"; |
| 08 | mysql_query($updatequery) or die(myql_error()); |
| 09 | //if checkbox IS NOT checked, update the database with a value of 0 |
| 10 | $updatequery2 = "update databasename set checkbox='0' where id NOT IN ($doSave)"; |
| 11 | mysql_query($updatequery2) or die(myql_error());} |
| 12 | if (!isset($_POST['checkbox'])){ |
| 13 | //if checkbox IS NOT set, update the database with a value of 0 |
| 14 | $doSave = implode(',',$_POST['checkbox']); |
| 15 | $updatequery2 = "update databasename set checkbox='0' where id NOT IN ($doSave)"; |
| 16 | mysql_query($updatequery2) or die(myql_error());} |
| 17 | } |
| 18 | ?> |
| 19 |
| HTML | | copy code | | ? |
| 1 | <form name="formname" action="" method="post"> |
The checkboxes are populated through a while loop (not shown). Each checkbox has the same name, but a unique value. The $id variable is the unique field that is populated from the database. Include brackets [] in order to turn the field into an array.
| PHP | | copy code | | ? |
| 1 | if($database['checkbox'] == 1) { $set_checked = "CHECKED";} |
| 2 | else{$set_checked = ""; } |
| 3 | print "<input type=\"checkbox\" name=\"checkbox[]\" value=\"$id\" $set_checked />"; |
| HTML | | copy code | | ? |
| 1 | <input name="doSave" type="submit" id="doSave" value="Save"></form> |


