codeigniter中未定义的偏移量

时间:2016-01-09 10:42:37

标签: php codeigniter

我在codegniter中创建了一个查询,用于以数组的形式更新数据,当我用3个字段更新数据时它工作正常但是当我尝试添加第4个字段然后我尝试更新数据时它表示未定义的偏移量3 | undefined offset 4不知道为什么会发生这种情况

public function update_content() {
    $i = 0;
    foreach($this->input->post() as $val):
        $heading = $this->input->post('heading')[$i];
        $span    = $this->input->post('span')[$i];
        $id      = $this->input->post('id')[$i];
        $type    = $this->input->post('type')[$i];
        $data = array(
            'heading' => $heading,
            'span'    => $span,
            'type'    => $type
        );
        $this->db->where('id', $id);
        $this->db->update('contentpage', $data);
        $i++;
    endforeach;
}

这是我的HTML

<input type="text" name="heading[]" size="20" value="<?php echo $data->heading; ?>" />
<input type="text" name="span[]" size="20" value="<?php echo $data->span; ?>" />
<input type="hidden" name="id[]" size="20" value="<?php echo $data->id; ?>" />
<input type="hidden" name="type[]" value="Default" />

2 个答案:

答案 0 :(得分:1)

试试这个编码...

public function update_content() {

    for($i = 0; $i < count($this->input->post('heading')); $i++) {
        $heading = $this->input->post('heading')[$i];
        $span    = $this->input->post('span')[$i];
        $id      = $this->input->post('id')[$i];
        $type    = $this->input->post('type')[$i];
        $data = array(
            'heading' => $heading,
            'span'    => $span,
            'type'    => $type
        );
        $this->db->where('id', $id);
        $this->db->update('contentpage', $data);

   }
}

否则替换以下编码

 foreach($this->input->post() as $val):

 foreach($this->input->post('heading') as $val):

答案 1 :(得分:0)

查找数组的大小和循环次数

$heading = $this->input->post('heading');
$span    = $this->input->post('span');
$id      = $this->input->post('id');
$type    = $this->input->post('type');
$count = sizeof($id);
for($i=0; $i<$count; $i++):
  if( $heading[$i]==''):
    $data = array(
        'heading' => $heading[$i],
        'span'    => $span[$i],
        'type'    => $type[$i]
    );
    $this->db->where('id', $id[$i]);
    $this->db->update('contentpage', $data);
  endif;
endfor;