CodeIgniter将多维数组作为单独的行插入到数据库表中

时间:2013-02-05 09:49:28

标签: php mysql codeigniter

将post值保存到数组中。

$data2 = array(
  'invoice_id' =>($id),
  'order_id' => $this->input->post('order_id'),
  'invoiceitems_servicetype' =>$this->input->post('type'),
  'invoiceitems_quantity' => $this->input->post('quantity'),
  'invoiceitems_unitprice' => $this->input->post('rate'),
  'invoiceitems_notes' => $this->input->post('description')
      );

 $this->db->insert('abc_invoiceitems', $data2);

print_r($data2);

数组结构。

Array
(
    [invoice_id] => 21
    [order_id] => 1
    [invoiceitems_servicetype] => Array
        (
            [0] => Order
            [1] => Miscellaneous
            [2] => Order
        )

    [invoiceitems_quantity] => Array
        (
            [0] => 5
            [1] => 64
            [2] => 88
        )

    [invoiceitems_unitprice] => Array
        (
            [0] =>  5
            [1] =>  6
            [2] =>  8
        )

    [invoiceitems_notes] => Array
        (
            [0] => test Data1
            [1] => test Data2
            [2] => test Data3
        )

)

将数组值插入数据库表。

TABLE NAME --- abc_invoiceitems 
 +------------+----------+--------------------------+-----------------------+------------------------+--------------------+
 | invoice_id | order_id | invoiceitems_servicetype | invoiceitems_quantity | invoiceitems_unitprice | invoiceitems_notes |
 +------------+----------+--------------------------+-----------------------+------------------------+--------------------+

我收到以下错误,错误是:

值以数组形式返回。

  

INSERT INTO abc_invoiceitemsinvoice_idorder_idinvoiceitems_servicetypeinvoiceitems_quantityinvoiceitems_unitpriceinvoiceitems_notes)VALUES(' 21','1',数组,数组,数组,数组)

2 个答案:

答案 0 :(得分:4)

获取帖子值:

$temp =count($this->input->post('type'));//counting number of row's
$type= $this->input->post('type');
$quantity = $this->input->post('quantity');
$rate = $this->input->post('rate');
$description = $this->input->post('description');

循环键值:

for($i=0; $i<$temp;$i++){
  $data2 = array(
  'invoice_id' =>($id),
  'order_id' => $this->input->post('order_id'),
  'invoiceitems_servicetype' =>$type[$i],
  'invoiceitems_quantity' => $quantity[$i],
  'invoiceitems_unitprice' => $rate[$i],
  'invoiceitems_notes' => $description[$i]
      );
   $this->db->insert('abc_invoiceitems', $data2);
  }

答案 1 :(得分:1)

如何将数组转换为serialized字符串?

$data2 = array(
    'invoice_id' =>($id),
    'order_id' => $this->input->post('order_id'),
    'invoiceitems_servicetype' => serialize($this->input->post('type')),
    'invoiceitems_quantity' => serialize($this->input->post('quantity')),
    'invoiceitems_unitprice' => serialize($this->input->post('rate')),
    'invoiceitems_notes' => serialize($this->input->post('description'))
);

$this->db->insert('abc_invoiceitems', $data2);

如果要将数据从数据库中拉回来,可以unserialize字符串。