i have been struggling.
I have a FORM that has a list of items. I only want to allow the selection of one item from this list and mark the item in my database as featured. I have tried radio buttons as well but the input name is different for each.
Form:
<td class="right"><input name="top_cat[<?php echo $cat['cat_id']; ?>][featured]" type="checkbox" class="featured" value="<?php echo $cat['featured'] ?>" />
</td>
Jquery on form:
$(function() {
$(".featured").each(function(){
if($(this).val() == 1){
$(this).attr('checked',"checked");
}
});
$(".featured").click(function(){
$(".featured").removeAttr('checked');
$(".featured").val('0');
$(this开发者_如何学Go).val('1');
$(this).attr('checked',"checked");
});
In my mysql update:
foreach ($data['top_cat'] as $cat_id => $value) {
$this->db->query("UPDATE " . DB_PREFIX . "cat SET featured='" . $this->db->escape($value['featured']) . "' WHERE cat_id = '" . (int)$cat_id . "'");
}
This works to a degree, it adds the value of "1" to the database for the item but leaves the previously checked item as "1", it needs to be "0".
I am sure i am over complicating this, any help or nudges in the right direction would appreciated.
POST will contain only the checked checkboxes, so your foreach loop is probably just looping once.
Use a radio button with the one name like top_cat
, the value will hold the $cat['cat_id']
. Now once you submit read the selected radio button with something like $_POST['top_cat']
or $data['top_cat']
Use radio button like:
<input name="top_cat" type="radio" class="featured" value="<?php echo $cat['cat_id'] ?>" />
and remove the loop and use php like:
$selected = (int)$data['top_cat'];
$this->db->query("UPDATE " . DB_PREFIX . "cat SET featured='1' WHERE cat_id = $selected ");
// set all others to non-featured
$this->db->query("UPDATE " . DB_PREFIX . "cat SET featured='0' WHERE cat_id != $selected ");
I am not sure how your database is setup but i think this should do the trick
i think because it is updating only currently selected item ,
so you need to run the update query which update to 0 all the previous item.
Try this:
$this->db->query("UPDATE " . DB_PREFIX . "cat SET featured='1' WHERE cat_id = '" . (int)$cat_id . "'");
foreach ($data['top_cat'] as $cat_id => $value) {
$this->db->query("UPDATE " . DB_PREFIX . "cat SET featured='0' WHERE cat_id = '" . (int)$cat_id . "'");
}
精彩评论