CodeIgniter更新不起作用

时间:2012-11-14 01:48:16

标签: codeigniter sql-update

我在模式中有一个表单,我用它来对记录进行更新。表单似乎提交正常,浏览器中的URL指向正确的位置(domain.net/cities/update_city/1)但没有显示视图,并且记录永远不会更新。我搜索了互联网,但大多数教程似乎都略过了更新或硬编码要更新的ID。我一直只使用CI一周。

型号代码

// Edit City
function edit_city($city_id) {
    $data = array('city_name' => $this->input->post('city_name'));
    $this->db->where('city_id', $city_id);
    $this->db->update('cities', $data);
}

查看代码(表单位于模态中,并通过jQuery添加city_id)

<div class="modal-body">
    <?php $this->load->helper('form'); ?>
        <?php echo form_open('/cities/update_city/'); ?>
        <label class="control-label" for="name">City</label>
        <input type="text" name="city_name" id="city_name" value=""/><br />
        <input type="submit" name="submit" class="btn-small btn-primary" value="Edit City" />
        <button class="btn-small" data-dismiss="modal">Cancel</button>
    <?php echo form_close(); ?>
</div>
<script>
  // scripts for modal windows
      $(document).on("click", ".edit-modal", function () {
      var city_name = $(this).data('name');
      var city_id = $(this).data('id');
      $(".modal-body #city_name").val( city_name );
      //set the forms action to include the city_id
      $(".modal-body form").attr('action','/cities/update_city/'+city_id);
      $('#editCityDialog').modal('show');
  });       

控制器代码

// Update City
function update_city($city_id) {
$this->load->model('cities_model');

    if ($this->input->post('submit')) {
        $data = array('city_name' => $this->input->post('city_name'));

        $this->cities_model->edit_city('cities', array('city_id' => $city_id),$data);
        redirect('/cities');
    }
}

1 个答案:

答案 0 :(得分:1)

这是一个例子,你可以用它来轻松更新(我很擅长英语,对不起)。

型号:

class Cities_model extends CI_Model{
    function edit($table,$where,$data){
       foreach ($where as $key => $value){
            $this->db->where($key,$value);
        }
        $this->db->update($table,$data);        
    }
}

控制器:

    function update_city($city_id){
    $this->load->model('cities_model');
         if($this->input->post('submit'){
         $data = array('city_name' => $this->input->post('city_name'));

         $this->cities_model->edit('cities',array('city_id' => $city_id),$data); //(table,where,data); see in model.
         redirect(''); 
         }
     }

* 如果你的链接是“http://......update_city/2”和一个函数update_city($ city_id),$ city_id将收到“2”并且你不需要写uri_segment来获得$ city_id。希望能帮到你

编辑:

控制器:

function update_city($city_id) {
$this->load->model('cities_model');

if ($this->input->post('submit')) {
    $this->cities_model->edit_city($city_id);
    redirect('/cities');
}

}