【问题标题】:Codeigniter - Update database records based on selected checkboxCodeigniter - 根据选中的复选框更新数据库记录
【发布时间】:2018-06-23 18:52:17
【问题描述】:

我有一个包含用户订单行的表,我希望用户能够一键更新多个订单行,所以我使用了一个复选框,以便用户可以检查想要更新的订单。

每个复选框表示如果选中则必须更新的订单 ID,我尝试使用循环,但代码会导致错误,或者什么也不做。

这是我的模型代码:

public function update_order(){
    $data = array(
      'status' => 'Pack'
    );
    $this->db->where('order_id', $this->input->post('checkbox'));
    return $this->db->update('user_orders', $data);
  }

控制器代码(为了更清楚,我放置了没有任何循环的代码):

public function update_order()
{
   $this->user_model->update_order();
}

最后是视图:

<?php echo form_open('user/update_order'); ?>
    <?php foreach ($users as $user): ?>
    <input type="checkbox" class="custom-control-input" name="checkbox" value="<?php echo $user['order_id']; ?>">
      <?php endforeach; ?>
      <button type="submit" class="btn btn-sm btn-block btn-warning text-white">Update</button>
 </form>

【问题讨论】:

    标签: php database codeigniter loops codeigniter-3


    【解决方案1】:

    希望对您有所帮助:

    使您的复选框成为这样的数组:checkbox[]

    你的视图应该是这样的:

    <?php echo form_open('user/update_order'); ?>
        <?php foreach ($users as $user): ?>
        <input type="checkbox" class="custom-control-input" name="checkbox[]" value="<?php echo $user['order_id']; ?>">
          <?php endforeach; ?>
          <button type="submit" class="btn btn-sm btn-block btn-warning text-white">Update</button>
     <?php echo form_close(); ?>
    

    你的update_order 方法应该是这样的:

    使用where_in更新记录

    public function update_order()
    {
        $data = array(
          'status' => 'Pack'
        );
        $order_ids = $this->input->post('checkbox');
        $this->db->where_in('order_id', $order_ids);
        return $this->db->update('user_orders', $data);
    }
    

    查看更多:https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data

    【讨论】:

    • 工作得很好,我想我需要在控制器中运行某种循环才能工作。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多