2013-04-12 65 views
1

我正在構建一個用戶可以成爲成員並具有最小配置文件的網站。儘管如此,在這個用戶希望更新他的記錄(關於我,電子郵件,電話號碼等)的情況下,我想要有一個鏈接「編輯個人資料」。一旦點擊了表單,就會加載輸入字段,其中的值由該用戶的數據庫記錄填充。他/她可以更改字段中的值,然後單擊保存更改,然後將這些值提交到數據庫。從codeigniter編輯數據庫記錄

我嘗試了幾次,但一直失敗。下面是我試過的形式加載數據的代碼:

public function load_edit() 
    { 
     //check user logged in 
     if(($this->session->userdata('username')!="")) 
     { 
      $data; 
      $result = $this->profileModel->load_user_editable_data($this->session->userdata('username')); 
      //check user data loaded successfully 
      if(isset($result)) 
      { 
       //get the user information and store to $data array 
       foreach($result as &$value) 
       { 
        $data = $value; 
       } 

       $this->load->view('profile_edit', $data); 
      } 
     }else{ 
      $this->login(); 
     }  
    } 

並更新數據庫表中的記錄:

public function update_edit() 
    { 

     $this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset|required|alpha_dash'); 


     if(isset($_POST)) 
     { 
      //check user logged in 
      if(($this->session->userdata('username')!="")) 
      { 
       //check that there are no form validation errors 
       if($this->form_validation->run() == FALSE) 
       { 
        $data = $this->profileModel->load_user_editable_data($this->session->userdata('username')); 
        $this->load->view('profile_edit', $data); 
       }else{ 
        $result = $this->profileModel->update_profile($this->session->userdata('username')); 
        if($result){ 

         $this->load->view('profile_edit', $result);    
        } 
       } 
      } 
     }else{ 
      $this->load->view('error'); 
     } 
    } 

我面臨着上面的代碼執行的主要問題是,不知何故,當我執行update_edit,它總是告訴我表單驗證失敗,即使滿足了字段的條件。

感謝提前:)

+1

你還沒有將$ data聲明爲數組,所以你一直覆蓋它的值。 – Rooneyl

回答

1

的幫助,我不知道驗證規則isset的。嘗試沒有它。

如果問題仍然存在,請在檢查isset($ _ POST)之前嘗試在update_edit中執行print_r($ _ POST)。同時檢查您的Session變量用戶名是否存在。

0

你可以用一個控制器的功能和更容易做到這一點:

public function edit($user_id = null) { 

     $data['url'] = "edit/$user_id"; // URL 
     $this->load->vars($data); // Load URL for FORM 
     $user = $this->profileModel->get_user($user_id); // Select USER by ID 

    if($this->input->post('save')) { 
     $this->form_validation->set_rules('username', 'Username', 'required'); 
     if($this->form_validation->run()) { 

      $user['username'] = $this->input->post('username'); // Get new username 
      $this->profileModel->edit($user); // Edit 
      // redirect somewhere. Edit done! 
     } 
    } 

    $this->load->view('content', 'profile_edit', $user); 
} 

下面是簡單的例子。你可以使用會話ID或帶參數的ID(就像我做的那樣)。

我希望你能理解