I have to insert roles for user by using check box but for inserting that i written a code like but it is inserting value ‘1’ 3 times (if selected 3 check boxes).
my HTML:
<tr>
<td align="right" width="47%" valign="top"><img
src="images/required_field.gif" /> User Role:</td>
<td width="40%" id="anstr"><input type="checkbox" id="roles_1"
value="1" name="roles[]" /> <label for="roles_1">X</label><span
id="levelRole"></span><br />
<input type="checkbox" id="roles_2" value="2" name="roles[]" /> <label
for="roles_2">Y</label><br />
<input type="checkbox" id="roles_3" value="3" name="roles[]" /> <label
for="roles_3">Z</label>
</td>
</tr>
my qry:
$roles = $_POST['roles'];
for ($i=0; $i<count($roles); $i++) {
$check_roles = implode(',', $_POST['roles']);
$sql1 = $db ->query ( "INSERT INTO user_role_xref( user_id, user_role_id, created_on)
VALUES ( :p_user_id, :p_user_role_id, :p_created_on)",
array (
'p_user_id' => 81,
'p_user_role_id' => $check_roles,
'p_created_on' => date("Y-m-d H:i:s")
)
);
}
Please help me how to do it.
i don’t really understand the
implode(',', $_POST['roles']). Should the roles be saved comma separated into one column? As the sql column saysuser_role_id, notids(plural) i would think there is a record for each separate role.First of all, try
foreach, much easier to read and write than a for loop, and it does the trick brilliantly. Try something like this;