2016-04-15 117 views
1

我编写了一个代码,使用codeigniter将输入数据插入到数据库中,但在插入之前,数据将通过if语句检查输入,然后如果满足条件,数据将被保存。使用if语句将数据插入数据库

我试图检查输入数据是否等于节,然后父id必须为0.否则,如果不是节,那么输入的$ data ['type']必须插入到数据库中并且父ID不能为0 。 这是我的代码。

$data = array (
'title' => $this->input->post->('title'), 
'type' => $this->input->post->('type'), 
'description' => $this->input->post->('description') 
); 


if ($data['type'] == 'section') { 
     $data['parent_id'] = 0; 
     } else { 
     $data['parent_id'] = $this->input->post('parent_id'); 
     $data['type'] = $this->input->post('type'); 
     } 
$result = $this->checklist_item_model->put_item($data); 

型号

public function put_item ($data) { 
    $this->db->insert('items', $data); 
} 
+0

你的插入查询或模型代码在哪里!! – Saty

+0

我编辑了上面的代码请看看 – claudios

回答

1

你可以创建你调理为

if($this->input->post('type')=='section') 
{ 
$data = array(
'title' => $this->input->post('title'), 
'type' => $this->input->post('type'), 
'description' => $this->input->post('description'), 
'parent_id' => 0// if section==0 condition 
); 
} else { 
    $data = array(
    'title' => $this->input->post('title'), 
    'type' => $this->input->post('type'), 
    'description' => $this->input->post('description'), 
    'parent_id' => $this->input->post('parent_id') 
    ); 
} 

$result = $this->checklist_item_model->put_item($data); 
+0

得到了一个错误的语法错误,意外的'(',期待标识符(T_STRING)或变量(T_VARIABLE)或'{'或'$' – claudios

+0

AHHH !!我坏的删除' - > '后检查!检查更新的答案!! – Saty

+0

代码运行,但我得到了同样的错误,它只插入部分输入 – claudios

1

您可以使用三元运算符简化代码

$data = array (
    'title' => $this->input->post('title'), 
    'type' => $this->input->post('type'), 
    'description' => $this->input->post('description'), 
    'parent_id' => ($this->input->post('parent_id') == 'section') ? 0 : $this->input->post('parent_id'); 
); 
$result = $this->checklist_item_model->put_item($data); 

而且,在你的模型可以返回最后一个插入ID像这样

public function put_item ($data) { 
    $this->db->insert('items', $data); 
    return $this->db->insert_id(); 
} 
+0

我会试试这个 – claudios

+0

这个也有帮助。Usi只有在其他情况下才是短型。 – claudios

+0

你的解决方案是好的,高效的只是删除' - >'之后,使其语法错误免费 – Saty