我使用的是Codeigniter MVC框架,我试图在DB中插入14行。此外,我的控制器中有14个对该模型的调用。然而不知怎么的,它只插入了周日早上。为什么?*我发布的视图只是每天(周一至周日(和(早上、晚上(重复的一小部分。
我的数据库是这样的:
+---------+---------+--------+
|天|时间|user_id|
+---------+---------+--------+
|星期日|上午|1|
+---------+---------+--------+
|星期一|晚上|1|
+---------+---------+--------+
型号
public function saveFinalShifts($data) {
$this->db->db_debug = FALSE;
$error = NULL;
if (!$this->db->insert_batch('final_shifts', $data)) {
$error = $this->db->error();
}
return $error;
}
控制器
public function saveFinalShifts(){
$data = array();
$dates = $this->input->post('date');
$days = $this->input->post('day[]');
$times = $this->input->post('time[]');
$worker_names = $this->input->post('worker_name[]');
if(is_array($dates)){
foreach ($dates as $key => $date){
$data[] = array (
'date' => $date,
'day' => $days[$key],
'time' => $times[$key],
'worker_name' => $worker_names[$key],
);
}
}
$this->Shifts_model->saveFinalShifts($data);
}
查看
<div class="warp">
<?php echo form_open('Shifts/savefinalShifts'); ?>
<table class="manage">
<th>
<input type="date" name="date[]">
</th>
<td>
<input type="hidden" value="sunday" name="day[]">
<input type="hidden" value="norning" name="time[]">
<?php
foreach ($sunday_morning as $shift):?>
<br><label><input class="get_value" type="checkbox" name="worker_name[]" value="<?php echo $shift['fullname'];?>">
<?php echo $shift['fullname'];
?></label>
<?php endforeach; ?>
</td>
<td>
<input type="hidden" value="monday" name="day[]">
<input type="hidden" value="morning" name="time[]">
<?php
foreach ($monday_morning as $shift):?>
<br><label><input class="get_value" type="checkbox" name="worker_name[]" value="<?php echo $shift['fullname'];?>">
<?php echo $shift['fullname'];
?></label>
<?php endforeach; ?>
</td>
</table>
<input type="submit" class="submit-btn" value=”send">
<div>
这是如果我打印$data数组的输出:
Array
(
[0] => Array
(
[date] => 2020-05-10
[day] => sunday
[time] => morning
[worker_name] => Victoria
)
)
您提交的所有输入post都是数组,但您只需在(day, time, worker_name
(中用[]
(如$this->input->post('day[]');
(选择post数据的第一个元素。尝试删除[]
,另外,将调用模型saveFinalShifts()
移动到if语句中,以确保在$dates
为数组(或不为空(时仅调用模型。
public function saveFinalShifts(){
$data = array();
$dates = $this->input->post('date');
$days = $this->input->post('day');
$times = $this->input->post('time');
$worker_names = $this->input->post('worker_name');
if(is_array($dates) && !empty($dates)){ // make sure $dates is array and not empty []
foreach ($dates as $key => $date){
$data[] = array (
'date' => $date,
'day' => $days[$key],
'time' => $times[$key],
'worker_name' => $worker_names[$key],
);
}
$this->Shifts_model->saveFinalShifts($data);
}
}
我认为错误的存在是因为您在controller function
中的foreach loop
之外写入query
。我已经在下面写了正确的代码,看看这是否对你有帮助。
if(is_array($dates)){
foreach ($dates as $key => $date){
$data = array (
'date' => $date,
'day' => $days[$key],
'time' => $times[$key],
'worker_name' => $worker_names[$key],
);
$this->Shifts_model->saveFinalShifts($data); //Move this line inside foreach loop
}
}