[英]How to send value if input not empty in insert batch CodeIgniter
基本上,我有这个将输入的值发送到数据库:
$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,然后将其添加到下一个代码块中,该代码块应检查imput是否为空。
提前致谢!。
该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);
我认为无需添加更多行就可以了
$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',
);
$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);
希望对你有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.