CodeIgniter - Checking to see if a radio button is checked in the database
Im having a bit of trouble putting some code together ... What im trying to do is add some code to the code i have at the moment to check radiobuttons that are checked in the database.
The code i have at the moment takes all roles from the database, outputs them using a foreach statement, but also splits the results into 2 columns, this is what i have at the moment.
<?php
$i = 0;
$output = "";
foreach($roles as $row){
if($i > 0){
$i = 0;
}
if($i == 0) {
$output .= "<div class='box'>";
}
$output .= '<div class="row">';
$output .= ' <input name="_'.$row->key.'" type="radio" id="'.$row->key.'" class="radio" />';
$output .= ' <label for="'.$row->key.'" style="text-transform: lowercase;">'.$row->name.'</label>';
$output .= '</div>';
if($i ==0) {
$output .= "</div>";
}
$i++;
}
if($i != 1) {
$output .= "</div>";
}
echo $output;
?>
Ok, so what i want to do is check the radio button in the code that i posted, only when there is a match in the database, So to get the values that were checked by the user, i use the following.
Model
function get_roles_by_id($freelancerid)
{
$query = $this->db->query('SELECT * FROM '.$this->table_name.' WHERE user_id = "'.$freelancerid.'"');
return $query->result();
}
Then my controller looks like this
$data['positions'] = $this->freelancer_roles->get_roles_by_id($freelancer_id);
As that is bring back an array i cant use a foreach statement to check the radio butt开发者_如何学Con id's that are returned in the positions array.
Could someone help me to figure this out.
Cheers,
I think I understand your question and it seems a fairly simple thing you are trying to do. If
You should have your model only return an array of the names of the checkboxes saved by the user in the following format: array("checkbox1", "checkbox2", "checkbox3") then in your output you can simply use the native php function in_array()
for example:
$output .= '<div class="row">';
$output .= ' <input name="_'.$row->key.'" type="radio" id="'.$row->key.'" class="radio"';
if(in_array($row->name, $data['positions']) { $output .= ' checked '; }
$output . = '/>';
$output .= ' <label for="'.$row->key.'" style="text-transform: lowercase;">'.$row->name.'</label>';
$output .= '</div>';
As a side note, you have the following code:
if($i > 0){
$i = 0;
}
if($i == 0) {
$output .= "<div class='box'>";
}
If you follow the logic in that code you will see that $i will always equal 0 for the second if statement, making both if statements redundant.
精彩评论