Ahmed iqbal Ahmed iqbal - 6 days ago 6
PHP Question

How to post data from repeated fields in codeigniter?

I'm using codeignter, I want to update my album sound tracks details. As you know, in album more then one sounds tracks available, so

<tr> </tr>
and all field under this repeated with total number of sound tracks.

Problem is that, how i can get all data from these fields and post to controller? if i need to use some sort of multidimensional array in name="" ? if yes, So how can i get data from array and pass to table?

Note: Just for clean code, i want to pass data from controller to Model. in Model i want to update in mysql.

View

<?php foreach ($soundtracks as $soundtrack) : ?>
<tr>
<td><input type="text" name="???" value="<?php echo $soundtrack->sound_title; ?>" /> </td>
<td><input type="text" name="???" value="<?php echo $soundtrack->sound_singer; ?>" /> </td>
<td><input type="text" name="???" value="<?php echo $soundtrack->sound_url; ?>" /></td>
</tr>
<?php endforeach; ?>


Controller

public function edit($id) {

// here we wan to pass sound tracks details in Model

$data = $this->album_m->array_from_post(array('cat_id', 'album_name', 'album_slug', 'album_title', 'album_description', 'album_keywords', 'album_composer', 'album_year'));
$this->album_m->save($data, $id);
redirect('admin/album/');
}


Model

public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;


}

public function save($data, $id = NULL){

// here just MYSQL update queries..


}

Answer

You have to set name for the fields as array

<?php foreach ($soundtracks as $soundtrack) : ?>
  <tr>
    <td><input type="text" name="title[]" value="<?php echo $soundtrack->sound_title; ?>" />   </td>
    <td><input type="text" name="singer[]" value="<?php echo $soundtrack->sound_singer; ?>" />  </td>
    <td><input type="text" name="url[]" value="<?php echo $soundtrack->sound_url; ?>" />
        <input type="text" name="track_id[]" value="<?php echo $soundtrack->id; ?>" />
    </td>
  </tr>
<?php endforeach; ?>

In controller,

$cnt =0 ;
$title = $this->input->post("title");
$singer = $this->input->post("singer");
$url = $this->input->post("url");
$ids = $this->input->post("track_id");
foreach($title as $t)
{
  echo $t. " - ".$singer[$cnt]."-".$url[$cnt]."-".$ids[$cnt];
  $cnt++;
}
Comments