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

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


而且我不断收到此错误:


  发生数据库错误
  错误编号:1364
  字段“ exp_user”没有默认值
  插入expenses()值(),(),(),(),(),(),(),(),(),(),(),()
  文件名:models / Expenses_model.php
  行号:26


这是我表的结构:

php - CodeIgniter insert_batch:字段“exp_user”没有默认值-LMLPHP

这是我要插入的示例:

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
}

最佳答案

如果变量$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 ) );

关于php - CodeIgniter insert_batch:字段“exp_user”没有默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40112404/

10-15 21:07