6

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.

4

5 に答える 5

8

ここで行う必要があるのは、この行を変更することです...

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

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

その理由は、値が 1 であるかどうかにかかわらず、変数 $checked が常に設定されるためです。がPOST データに設定されていない$checked = $this->input->post('remove');場合は NULL を返します。'remove'

于 2013-09-25T06:47:27.277 に答える
1

試す:

<input id="remove" type="checkbox" name="remove" value="1">
于 2013-09-25T06:39:53.880 に答える
1

削除するisset

その理由は、デフォルトでCIコントローラーで次を使用して入力値を取得するためです

$checked = $this->input->post('remove');

値があるかどうか、変数が存在するかどうか..

于 2013-09-25T06:53:27.120 に答える
0

役立つ場合はこれを使用してください。

$checked = (isset($_POST['checkbox']))?true:false;
于 2018-09-04T09:27:15.727 に答える