Forum Moderators: coopster

Message Too Old, No Replies

Repopulating checkboxes from mysql database

         

upperbid

2:23 am on Jun 29, 2009 (gmt 0)

10+ Year Member



I am having a difficult time repopulating user checkbox selections from a mysql database. It is currently stored with selections as numbers in one field called PaymentMethods in the specified table. I have figured out how to successfully explode it and get the results that are there (it only stores the numbers of those selected and ignores blanks ones when writing to the database). My problem is I'm trying to have all the checkboxes appear with the user database results resulting in the proper checkboxes being checked. So far I have this:

$pmethods = explode("¦¦", $r2["PaymentMethods"]);
$choices = array('1'=>"Cashiers Check",'2' => "Money Order",'3'=>"Personal Check",'4'=>"Credit Card",'8'=>"PayPal");
foreach ($choices as $key6 => $value6) {
$checked = ($pmethods == $key6) ? ' checked="checked"' : '';
echo "<input type=\"checkbox\" name=\"methods[]\" value=\"$key6\" $checked />$value6";
echo "</br>";
}

This only shows the checkboxes and none of them checked.

My other attempt has been:

foreach ($pmethods as $key => $value2) {

if ($value2=="10"){
print "<input type=\"checkbox\" name=\"methods[]\" value=\"Cash\" checked=\"checked\" />Cash";
}
if (($value2=="1") OR ($value2=="3")){
print "<input type=\"checkbox\" name=\"methods[]\" value=\"Check\" checked=\"checked\" />Check";
}
if ($value2=="2"){
print "<input type=\"checkbox\" name=\"methods[]\" value=\"Money Order\" checked=\"checked\" />Money Order";
}
if (($value2=="4") OR ($value2=="5") OR ($value2=="6") OR ($value2=="7")){
print "<input type=\"checkbox\" name=\"methods[]\" value=\"Credit Card\" checked=\"checked\" />Credit Card";
}
if ($value2=="8"){
print "<input type=\"checkbox\" name=\"methods[]\" value=\"Paypal\" checked=\"checked\" />PayPal";
}

}

The problem with this method is that it only shows the checked boxes and not the unchecked ones which need to be shown as well.

Any help would be appreciated. Thanks.

jatar_k

2:39 pm on Jun 29, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld upperbid,

you just need to move your if statement. You want to always show the checkbox but only check it if it is checked. So the portion of the checkbox html that makes it appear checked is all you need to surround with an if

print "<input type=\"checkbox\" name=\"methods[]\" value=\"Paypal\";
if ($value2=="8") echo ' checked="checked"';
echo " />PayPal";
}

something like that