Update multiple rows with same id using foreach lo

2019-08-30 19:24发布

问题:

I echo 2 input-fields (2 db columns) foreach row in the database (where id=$id) with each row's data being inside the input field. Admin-user can change data inside input-field and click update.

Currently, when clicking the update-button, it does update the rows (where id=$id) but it updates each row with the input-data of the first input field instead of updating input-data foreach input field. Thank you in advance for help.

view:

<form action='<?= site_url("admin/do_edit_page"); ?>' method='POST'>
    <?php foreach($link_data as $row) : ?>
        Link:<br />
        <input type='text' name='page_link_title' value='<?= $row->link_title; ?>'>
        <input type='text' name='page_link_sub_title' value='<?= $row->link; ?>'><br />
    <?php endforeach; ?>

        <input type='submit' name='update_site' value='Update'>
</form>

controller:

public function do_edit_page(){
    $id = $this->input->post('page_id', TRUE);
    $this->content_model->update_links($id);
}

model:

public function update_links($id){
    foreach($_POST as $update_rows){
        $update_rows = array(
            array(
              'page_id' => $id,
              'link_title' => $this->input->post('page_link_title', TRUE),
              'link' => $this->input->post('page_link_sub_title', TRUE)  
            )
        );
        $this->db->update_batch('content_links', $update_rows, 'page_id');  
    }  
}

回答1:

you have to move your form tag between the foreach loop so that it can submit the data of single row. something like this

<?php foreach($link_data as $row) : ?>
  <form action='<?= site_url("admin/do_edit_page"); ?>' method='POST'>
    Link:<br />
    <input type='text' name='page_link_title' value='<?= $row->link_title; ?>'>
    <input type='text' name='page_link_sub_title' value='<?= $row->link; ?>'><br />
    <input type='submit' name='update_site' value='Update'>
  </form>
<?php endforeach; ?>