Checkbox Assignment

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
icesolid
Forum Regular
Posts: 502
Joined: Mon May 06, 2002 9:36 pm
Location: Buffalo, NY

Checkbox Assignment

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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..
Post Reply