基本上,我具有将输入的值发送到数据库的功能:
$tag = $this->input->post('tags[]');
$data = array();
foreach ($tag as $term){
$data[] = array(
'post_id' => $post_id,
'term_id' => $term,
'user_id' => $this->input->post('user_id'),
'status' => 'attached',
'type' => 'tag',
);
}
$this->db->insert_batch('ci_relationship', $data);
但是我试图通过使管理员输入X用户作为值或会话user_id(如果他决定将其保留为空)来使user_id为“可选”。
我尝试执行此操作,但仍然无法正常工作
$tag = $this->input->post('tags[]');
$data = array();
foreach ($tag as $term){
$data[] = array(
'post_id' => $post_id,
'term_id' => $term,
//'user_id' => $this->input->post('user_id'),
'status' => 'attached',
'type' => 'tag',
);
}
$user_id = $this->input->post('user_id');
if(empty($user_id)){
$data['user_id'] = $this->session->userdata('user_id');
} else {
$data['user_id'] = $user_id;
}
$this->db->insert_batch('ci_relationship', $data);
如您所见,我在foreach中注释了user_id,然后将其添加到下一个代码块中,该代码块应检查输入是否为空。
提前谢谢!。
答案 0 :(得分:0)
if语句必须在foreach中。
$tag = $this->input->post('tags[]');
$user_id = $this->input->post('user_id');
$data = array();
foreach ($tag as $key => $term){
$data[$key] = array(
'post_id' => $post_id,
'term_id' => $term,
'status' => 'attached',
'type' => 'tag',
);
if(empty($user_id)){
$data[$key]['user_id'] = $this->session->userdata('user_id');
} else {
$data[$key]['user_id'] = $user_id;
}
}
$this->db->insert_batch('ci_relationship', $data);
答案 1 :(得分:0)
我认为无需添加更多行,只需在侧面进行此操作
$data[] = array(
'post_id' => $post_id,
'term_id' => $term,
'user_id' => (!empty($this->input->post('user_id')) ? $this->input->post('user_id') : '',
'status' => 'attached',
'type' => 'tag',
);
答案 2 :(得分:0)
$tag = $this->input->post('tags[]');
$data = array();
foreach ($tag as $key => $term){
if(empty($this->input->post('user_id')))
{
$data[$key] = array(
'post_id' => $post_id,
'term_id' => $term,
'status' => 'attached',
'type' => 'tag',
);
}
else
{
$data[$key] = array(
'post_id' => $post_id,
'term_id' => $term,
'user_id' => $this->input->post('user_id'),
'status' => 'attached',
'type' => 'tag',
);
}
}
$this->db->insert_batch('ci_relationship', $data);
希望它对您有用。