2013-09-25 61 views
5

我使用CodeIgniter,並且我有一個帶有複選框的表單,允許用戶檢查並刪除他們上傳的照片。
在我的控制器中,我使用if(isset($checked) == 1)來檢查用戶是否要刪除照片。
$photo_to_table將設置爲空並通過$this->tank_auth->update_user()執行數據庫更新,並將表中的照片字段設置爲空。否則,它將保持相同的照片。
Codeigniter檢查複選框的值

但在我的代碼中,無論是否檢查它,當我點擊UPDATE按鈕時,它會一直刪除照片,我不知道爲什麼會發生這種情況?

有人可以通過我的代碼並給出建議嗎?

控制器:

$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()); 
    } 
} 

查看:

<?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 
} 
?> 

感謝。

回答

6

你需要在這裏做的是改變這一行...

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

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

的原因在於,變量$檢查將始終設置是否其值是1或不是。如果未在POST數據中設置'remove',則$checked = $this->input->post('remove');將返回NULL。

+0

。同意它.. –

+0

非常感謝你:) – conmen

3

請在您的複選框寫適當的值: -

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

寫了一些值,那麼檢查: -

爲如:

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

在PHP中: -

if($checked == 1) { 
     // do whatever u want 
    } 
+0

我追加的輸入值'value =「1」'但它仍然不起作用。 – conmen

1

Try:

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

我加了'value =「1」',仍然是一樣的。首先是 – conmen

1

刪除isset

它,因爲默認情況下,在你的CI控制器你使用

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

在於是否具有價值或者不是你的變量現在存在..