Monday, June 13, 2016

Update Multiple Records Based On Radio Buttons Using FOR EACH

Today I will share a code snippet which will enable you to update multiple records based on radio buttons selection.

Consider this scenario:

Players are applying to play for a football team. There are more players than there are places, so some will get to play for the First team, some for the B team, some will be in the Reserves, and some will not get selected at all.

If you want to be able to pull up all players and assign their application result in the database in one update process.

Now you can do it using FOR EACH as shown in the snippet below:


foreach ($_POST[result] as $id => $result) {

$results[$result][] = $id;

}

$query = "UPDATE tablename SET result = CASE ";

foreach ($results as $res => $ids) {

$query .= sprintf("WHEN id IN (%s) THEN %s ", join(,, $ids), $res);

}

$query .= END;


Hope php script can guide you in the right direction.

Enjoy!