Page 1 of 1

Checkbox Assignment

Posted: Wed Sep 12, 2007 12:30 pm
by icesolid
I have a list of checkboxes like below:

Code: Select all

$username = $row["username"];

$result = mysql_query("SELECT * FROM users WHERE account_type='1' ORDER BY username ASC");

while($row = mysql_fetch_array($result)) {
    $result1 = mysql_query("SELECT * FROM users WHERE username='$username'");
    $row1 = mysql_fetch_array($result1);

    if($row["corporate"] == $row1["username"]) {
        $checked = " checked";
    } else {
        $checked = "";
    }

    echo "<input type=\"checkbox\" name=\"userID[" . $row["id"] . "]\"$checked>" . $row["username"] . "<br>\n";
}
When the form is submitted I then run this code:

Code: Select all

foreach($_POST["userID"] as $userID => $check) {
    mysql_query("UPDATE users SET corporate='$username' WHERE id='$userID'");
}
Right now that code only will se corporate='$whatever' when boxes are selected. I also want it to set corporate='' if a box is unselected and then submitted.

Posted: Wed Sep 12, 2007 12:36 pm
by John Cartwright
If you run a

Code: Select all

mysql_query("UPDATE users SET corporate='' WHERE id NOT IN(". implode(', ', array_keys($_POST["userID"]))) .''");
prior to updating your records, records that arn't currently submitted will be removed.

Don't forget to validate $_POST['userID'] before running this though..

This is also assuming all your listings of your database on a single page, don't try with pagination.. however since you didn't mention this..