【问题标题】:Insert_batch CodeIgniterInsert_batch CodeIgniter
【发布时间】:2015-05-26 19:09:50
【问题描述】:

我正在尝试使用带有 CodeIgniter 的函数 insert_batch 将来自表单的一些值插入为数组。

这是控制器中的代码:

$data_product = array(
'quantity'=> $quantity,
'price'=> $price,
'productID'=> $product_id
);

$this->load->model('product_ordered');
$this->product_ordered->insert_quantity_products($data_product);

这是模型 insert_quantity_products

中的代码
public function insert_quantity_products($data){
$this->db->insert_batch('orders', $data);
}

这是数据库错误

Unknown column '0' in 'field list'
INSERT INTO `orders` (`0`, `1`, `2`) VALUES ('3','1','1'),
('358.00','458.00','324.00'), ('1','39','69')

未知列应该是数量、价格和产品ID

我做错了什么?

【问题讨论】:

  • insert_batch 函数使用二维数组,但您使用的是一维数组。

标签: php codeigniter


【解决方案1】:

在控制器中

$this->load->model('product_ordered');
$this->product_ordered->insert_quantity_products();

在模型中

  1. 如果您使用单输入,请使用此($this->db->insert)

    public function insert_quantity_products() { $data_product = array( 'quantity'=> $quantity, 'price'=> $price, 'productID'=> $product_id );
    $this->db->insert('orders', $data_product); }

// 产生:INSERT INTO orders (quantity, price, productID) VALUES ('$quantity', '$price', '$product_id')

  1. 如果您要批量插入,请使用此 ($this->db->insert_batch)

    public function insert_quantity_products() { $data_product = array( array( 'quantity'=> $quantity, 'price'=> $price, 'productID'=> $product_id ); array( 'quantity'=> $quantity2, 'price'=> $price2, 'productID'=> $product_id2 ); ); $this->db->insert_batch('orders', $data_product); }

// 产生:INSERT INTO orders (quantity, price, productID) VALUES ('$quantity', '$price', '$product_id'),('$quantity2', '$price2', '$product_id2')

【讨论】:

    【解决方案2】:

    您尝试使用函数insert_batch

    所以检查文档:

    第一个参数将包含表名,第二个参数是值的关联数组。

    $data = array(
       array(
          'title' => 'My title' ,
          'name' => 'My Name' ,
          'date' => 'My date'
       ),
       array(
          'title' => 'Another title' ,
          'name' => 'Another Name' ,
          'date' => 'Another date'
       )
    );
    

    这是您必须如何设置数据的示例。

    【讨论】:

    • 嗨,我也有同样的问题。该列未被识别“字段 lis”中的未知列“0”
    • 在您只插入一行的情况下,您可以尝试使用insert 而不是insert_batch 并将您的数据设置为一维数组中的数据
    【解决方案3】:

    您需要为 $data_product 使用二维数组。 这意味着您控制器更改 $data_product 如下:

    $data_product[] = array('quantity'=> $quantity, 'price'=> $price, 'productID'=> $product_id);

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 2015-01-28
      • 2014-02-07
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      相关资源
      最近更新 更多