foreach문 db저장
본문
안녕하세요~제가 아래와 같은 코드를 만들었는데요 db저장하는데 어려움을 겪고 있어서요,,
foreach ($posting as $detail) {
if ($detail->posting_type == 0) {
?>
<tr>
<input type="hidden" name="posting_type" value="0">
<td><input type="hidden" name="report_day" value="<?=$detail->report_day?>"><?=$detail->report_day?>일</td>
<td><input type="hidden" name="hospital_id" value="<?=$detail->hospital_id?>"><?=$detail->hosp_name?></td>
<td name="last_month"><input type="hidden" name="last_month" value="<?=$detail->last_month?>"><?=$detail->last_month?>개</td>
<td name="total"><input type="hidden" name="total" value="<?=$detail->total?>"><?=$detail->total?>개</td>
<? for($i=0;$i<$maxDay;$i++){ ?>
<td name="posting_day"><?php echo $daily[$i]; ?>
</td>
<? } ?>
<td name="last_month"><?=$detail->last_month?>개</td>
</tr>
<?php
} //if
} //foreach
?>
위의 코드를 db에 저장하고 싶은데 아무리해도 마지막 데이터만 저장이 되네요,,, 어떤 방법을 사용하는게 좋을까요..? 감사합니다~~ 아래는 혹시 몰라서 컨트롤러 부분 첨부합니다..
$posting_data = array(
'report_day' => $this->input->post('report_day'),
'last_month' => $this->input->post('last_month'),
'posting_user_id' => $this->input->post('posting_user_id'),
'total' => $this->input->post('total'),
'posting_type' => $this->input->post('posting_type'),
'hospital_id' => $this->input->post('hospital_id'),
'posting_day' => $this->input->post('posting_day'),
);
$this->posting_models-> save_posting($posting_data);
답변 3
안뇽하세용 님 말씀처럼 input의 name을 전부 배열로 만들어서 넘기신 후에 controller 단에서 아래처럼 수정하면 되지 않을까 싶네요.
$post = $this->input->post(null, true);
$posting_data[] = [
'report_day' => $post['report_day'],
...생략...
'posting_day' => $post['posting_day']
];
$this->posting_models->save_posting($posting_data);
배열로 넘기시면 되니까 model에서는 save_posting 부분을 insert_batch로 받으시면 됩니다.
public function save_posting($data) {
return $this->db->insert_batch("테이블", $data);
}
name 값을 배열로 줘서 posting_type[] 이런식으로주고
받는쪽에서도 배열길이 체크해서 for문 돌리세여
foreach ($posting as $detail) {
?><input type="hidden" name="posting_type" value="0">
}
loop를 사용하는 경우
<input name을 동일 하게 사용하는 경우
맨 마지막 것, 혹은 맨 처음 것만 처리됩니다.
보통 이럴 때는
?><input type="hidden" name="posting_type[]" value="0">
이렇게 처리합니다.
받는 쪽(php)에서도 배열에 맞게 해 주어야 합니다.