CodeIgniter insert_batch:字段'exp_user'没有默认值

时间:2016-10-18 15:34:13

标签: php mysql codeigniter

我正在尝试将数组作为一行插入到我的数据库中的“费用”表中:

public function insert_expense($expenses){
    $this->db->insert_batch('expenses', $expenses); 
}

我一直收到这个错误:

  

发生数据库错误
  错误号码:1364
  字段'exp_user'没有默认值
  INSERT INTO expenses()VALUES(),(),(),(),(),(),(),(),(),(),(),()
  文件名:models / Expenses_model.php
  行号:26

这是我桌子的结构:

enter image description here

这是我试图插入的一个例子:

array(12) {
    ["exp_user"] "1"
    ["exp_date"] "2016-10-18"
    ["exp_date_request"] "2016-10-18"
    ["exp_client"] "Potato"
    ["exp_provider"] "Miew"
    ["exp_amount"] "1"
    ["exp_currency"] "₪"
    ["exp_budget"] "budget2"
    ["exp_method"] "cc"
    ["exp_frequency"] "Monthly"
    ["exp_expenditure"] "asdasdas asdas dsa as"
    ["exp_charge_client"] NULL
}

1 个答案:

答案 0 :(得分:2)

如果变量$expenses是您示例中的数组:

$expenses = array(
    "exp_user" => "1",
    "exp_date" => "2016-10-18",
    "exp_date_request" => "2016-10-18",
    "exp_client" => "Potato",
    "exp_provider" => "Miew",
    "exp_amount" => "1",
    "exp_currency" => "₪",
    "exp_budget" => "budget2",
    "exp_method" => "cc",
    "exp_frequency" => "Monthly",
    "exp_expenditure" => "asdasdas asdas dsa as",
    "exp_charge_client" => NULL
);

您无法在insert_batch函数中使用它(因为insert_batch函数需要获取一组数组(数据)作为第二个参数)。

基本上insert_batch函数可以插入多行(不需要循环insert函数)。您可以使用多维数组:

$expenses = array(
    array(
        "exp_user" => "1",
        "exp_date" => "2016-10-18",
        "exp_date_request" => "2016-10-18",
        "exp_client" => "Potato",
        "exp_provider" => "Miew",
        "exp_amount" => "1",
        "exp_currency" => "₪",
        "exp_budget" => "budget2",
        "exp_method" => "cc",
        "exp_frequency" => "Monthly",
        "exp_expenditure" => "asdasdas asdas dsa as",
        "exp_charge_client" => NULL
    ),
    array(
        "exp_user" => "1",
        "exp_date" => "2016-10-18",
        "exp_date_request" => "2016-10-18",
        "exp_client" => "Potato",
        "exp_provider" => "Miew",
        "exp_amount" => "1",
        "exp_currency" => "₪",
        "exp_budget" => "budget2",
        "exp_method" => "cc",
        "exp_frequency" => "Monthly",
        "exp_expenditure" => "asdasdas asdas dsa as",
        "exp_charge_client" => NULL
    ),
    array(
        "exp_user" => "1",
        "exp_date" => "2016-10-18",
        "exp_date_request" => "2016-10-18",
        "exp_client" => "Potato",
        "exp_provider" => "Miew",
        "exp_amount" => "1",
        "exp_currency" => "₪",
        "exp_budget" => "budget2",
        "exp_method" => "cc",
        "exp_frequency" => "Monthly",
        "exp_expenditure" => "asdasdas asdas dsa as",
        "exp_charge_client" => NULL
    )
);

现在使用insert_batch

是有道理的

如果您只想插入1条记录,可以使用insert功能:

$this->db->insert('expenses', $expenses); 

或将通话更改为:

$this->db->insert_batch('expenses', array( $expenses ) );