Ahmad Tahhan
Ahmad Tahhan

Reputation: 125

Codeigniter - Update database records based on selected checkbox

I have a table that contains rows of user orders, I would like the user to be able to update multi orders rows in one click, so I am using a checkbox so the user can check the order that would like to update.

each checkbox represents the order id that has to be updated if checked, I tried to use loops, but the code else cause an error, or do nothing.

here is the my model code:

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

Controller code (I placed the code without any loops just to make it more clear):

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

and finally here is the view:

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

Upvotes: 0

Views: 1381

Answers (1)

Pradeep
Pradeep

Reputation: 9707

Hope this will help you :

Make your checkbox an array like this : checkbox[]

Your view should be like this :

<?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(); ?>

Your update_order method should be like this :

Use where_in to update the records

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

See more : https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data

Upvotes: 2

Related Questions