[英]how to save multiple rows in mysql using codeigniter
我有一个旅馆网站的表单,我想在其中更新其服务,而客户希望一次更新多个服务。 但是,我不知道如何使用模型将其保存在数据库中。
我已经建立了控制器,它看起来像这样:
$items = array(
array(
'id' => $this->input->post('id1', true),
'hotel_id' => $hotel_id,
'des_servicio' => $this->input->post('des_servicio1', true),
'est_activo' => $this->input->post('est_activo1', true)
),
array(
'id' => $this->input->post('id2', true),
'hotel_id' => $hotel_id,
'des_servicio' => $this->input->post('des_servicio2', true),
'est_activo' => $this->input->post('est_activo2', true)
),
array(
'id' => $this->input->post('id3', true),
'hotel_id' => $hotel_id,
'des_servicio' => $this->input->post('des_servicio3', true),
'est_activo' => $this->input->post('est_activo3', true)
)
);
$this->hotel_model->save_multiple($items);
[更新]
这是我的新模型的样子:
function save_multiple($items = array())
{
$this->db->insert_batch($this->__tabla, $items);
return $this->db->affected_rows();
}
我的问题是,即使我仅填充3个字段,它现在也会创建10行(我的原始表单具有10个字段)。 因此,在我的数据库中,存储了3个服务以及7个空白行。 如何改变呢?
foreach $items //I get an error here
as $item
应该
foreach ( $items as $item )
请记住,如果未设置值,则input-> post()返回false。 因此,请检查该值是否设置为将其放入数组中。 然后当模型收到它时。 它保存了所有。 或另一个选择是从传入的数组在模型中创建一个新数组,然后将新数组传递给insert_batch()函数。
$items = array();
$id = $this->input->post('id1', true);
if( $id != false ) {
$items[] = array(
'id' => $id, true),
'hotel_id' => $hotel_id,
'des_servicio' => $this->input->post('des_servicio1', true),
'est_activo' => $this->input->post('est_activo1', true)
);
}
$id = $this->input->post('id2', true);
if( $id != false ) {
$items[] = array(
'id' => $id, true),
'hotel_id' => $hotel_id,
'des_servicio' => $this->input->post('des_servicio2', true),
'est_activo' => $this->input->post('est_activo2', true)
);
}
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.