首页 文章

使用if语句将数据插入数据库

提问于
浏览
1

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

我试图检查输入数据是否等于section然后父id必须为0.否则如果不是section则输入的$ data ['type']必须插入数据库,而parent 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);
 }

2 回答

  • 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);
    
  • 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();
    }
    

相关问题