views:

560

answers:

1

Hello

I have about 8 check boxes that are being generated dynamically from my database.

This is the code in my controller

//Start Get Processes Query
    $this->db->select('*');
    $this->db->from('projects_processes');
    $this->db->where('process_enabled', '1');
    $data['getprocesses'] = $this->db->get();
    //End Get Processes Query

    //Start Get Checked Processes Query
    $this->db->select('*');
    $this->db->from('projects_processes_reg');
    $this->db->where('project_id', $project_id);
    $data['getchecked'] = $this->db->get();
    //End Get Processes Query

This is the code in my view.

<?php if($getprocesses->result_array()) { ?>
<?php foreach($getprocesses->result_array() as $getprocessrow): ?>
<tr>
    <td><input <?php if($getchecked->result_array()) { foreach($getchecked->result_array() as $getcheckedrow): if($getprocessrow['process_id'] == $getcheckedrow['process_id']) { echo 'checked'; } endforeach; }?> type="checkbox" name="progresscheck[]" value="<?php echo $getprocessrow['process_id']; ?>"><?php echo $getprocessrow['process_name']; ?><br>
    </td>
</tr>
<?php endforeach; ?>

This generates the checkboxes into the form and also checks the appropriate ones as specified by the database.

The problem is updating them.

What I have been doing so far is simply deleting all checkbox entries for the project and then re-inserting all the values into the database. This is bad because 1. It's slow and horrible. 2. I lose all my meta data of when the check boxes were checked.

So I guess my question is, how do I update only the checkboxes that have been changed?

Thanks, Tim

+1  A: 

Hi Tim,

First, you have two database queries, and then a nested loop inside your view. It would be much better to have one query with a join statement -- something like JOIN ON projects_processes.process_id = projects_processes_reg.process_id WHERE process_enabled=1 AND project_id=$project_id.

Second, the names of your form elements are just progresscheck[] - you should probably explicitly name the array number with the process_id so that you can cross-reference back to the DB.

Then, to update only checkboxes that have been changed, when the form is POSTed:
- Re-run the new, single query you use to generate the checkboxes
- Iterate through the result, checking the $_POST array (or CI's set_value() function) for changed values - Run an update statement when you find a changed value.

Good luck!!

~S

Summer