Php 如何使用codeigniter在mysql中保存多行
我有一个酒店网站的表单,在那里我想更新它的服务,而客户想一次更新多个服务。但是,我不知道如何将它保存在模型的数据库中 我已经构建了我的控制器,它看起来像这样:Php 如何使用codeigniter在mysql中保存多行,php,mysql,codeigniter,Php,Mysql,Codeigniter,我有一个酒店网站的表单,在那里我想更新它的服务,而客户想一次更新多个服务。但是,我不知道如何将它保存在模型的数据库中 我已经构建了我的控制器,它看起来像这样: $items = array( array( 'id' => $this->input->post('id1', true), 'hotel_id' => $hotel_id,
$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();
}
我的问题是,现在它创建了10行(我的原始表单有10个字段),即使我只填充了3个字段。所以在我的数据库中存储了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)
);
}
....
您可能还需要查看$this->db->insert_batch('mytable',$items)@Aaron谢谢这非常有帮助,但是现在我遇到了我提到的问题,字段不是可选的,当我不填充它们时,它会创建空行。正如我提到的,我的原始表单有10个字段,所以当我只填充2或3个字段时,数据库中仍然会创建10行。你知道怎么改吗?哦,那只是我打字时犯的一个最大的错误,很抱歉我的原始代码中有括号。我现在就试试你说的插页批次。谢谢!我做了类似的操作,然后使用array_filter()删除空数组,以便再次将其传递给insert_batch(),谢谢您的时间:)