Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter checking checkbox value

I'm using CodeIgniter and I have a form with a checkbox that allows the user to check and remove their uploaded photo.
In my controller I use if(isset($checked) == 1) to check if the user wants to remove the photo.
$photo_to_table will set empty and pass to $this->tank_auth->update_user() to perform db update, and set photo field to become empty in table. Otherwise, it will remain the same photo.

But in my code, whether I check it or not, when I click UPDATE button, it keeps removing the photo, I wonder why is it happening?

Can someone please go through my code and give an advise?

Controller:

$user_id = $this->session->userdata('user_id');
$profile = $this->users->get_profile_by_id($user_id);

if(!empty($_FILES['photo']['name'])) 
{
    //image upload process
}
else
{
    $checked = $this->input->post('remove');
    if(isset($checked) == 1)
        {
            $photo_to_table = '';
            // here will do remove process to delete file in directory
        }
    else
    {
        $photo_to_table = $profile->photo;
    }
}

    if($this->form_validation->run()) { // validation ok
    if(!is_null($data = $this->tank_auth->update_user(
        $this->form_validation->set_value('name'),
        $this->form_validation->set_value('country'),
        $this->form_validation->set_value('website'),
        $photo_to_table
        ))) 
    { 
        // success
        $this->session->set_flashdata('msg', 'Profile has been updated');
        redirect(current_url());
    }
}

View:

<?php echo form_open_multipart($this->uri->uri_string()); ?>
<table border="0">

<?php
if(!empty($uphoto)){
?>
    <tr>
        <td>
            <div>
                <img src="<?php echo base_url().$userpath.$uphoto; ?>" />
           </div>

           <div>
               <input id="remove" type="checkbox" name="remove">
               <label for="remove">Remove photo</label>
           </div>
       </td>
   </tr>
<?php
}
?>

Thanks.

like image 962
conmen Avatar asked Sep 25 '13 06:09

conmen


2 Answers

What you need to do here is to change this line ...

if(isset($checked) == 1){

to

if((int) $checked == 1){

The reason is that the variable $checked will always be set whether its value is 1 or not. $checked = $this->input->post('remove'); will return NULL if the 'remove' is not set in the POST data.

like image 186
TigerTiger Avatar answered Oct 15 '22 02:10

TigerTiger


Please write proper value in your checkbox :-

   <input id="remove" type="checkbox" name="remove">

Write some value then check it :-

for e.g :

  <input id="remove" type="checkbox" name="remove" value="1">

In php :-

   if($checked == 1) {
      // do whatever u want
   }
like image 3
Roopendra Avatar answered Oct 15 '22 03:10

Roopendra