如何在Codeigneitor中同时向数据库插入多个记录

时间:2016-06-21 09:16:10

标签: php mysql codeigniter

我想通过做一些计算将一些值插入数据库中我已经获得这些值。现在我可以在html报告中查看这些值。但我想要做的是将这些多个值插入数据库有50个人。所以我想通过点击一个按钮同时添加这50个人的所有细节。我能做到这一点吗?可能是我的控制器视图和模型。

以下是我在控制器

中计算后得到的值
$sheet_data[] = array(
    "employee_id" => $emp,
    "name" => $allEmp->name,
    "gender" => $allEmp->gender,
    "br_allow" => $allEmp->allowance,
    "work_days" => $working_days,
    "holiday_ot_hrs" => $holiday_ot_hrs,
    "holiday_ot_dys" => $holiday_ot_dys,
    "holiday_ot_amount" => $holiday_ot_amount
);

2 个答案:

答案 0 :(得分:0)

您可以为批量插入

创建这样的数组
$data = array(
   array(
      'employee_id' => $emp ,
      'name' => $allEmp->name, ,
      'gender' => $allEmp->gender,
   ),
   array(
       'employee_id' => $emp ,
      'name' => $allEmp->name, ,
      'gender' => $allEmp->gender,
   )
);

$this->db->insert_batch('mytable', $data); 

使用批量插入可以插入多个记录 有关详细信息,请参阅此链接:https://www.codeigniter.com/userguide3/database/query_builder.html

希望这会对你有所帮助。

答案 1 :(得分:0)

首先,你必须为你的记录创建数组。

$sheet_data[0] = array(
    "employee_id" => $emp,
    "name" => $allEmp->name,
    "gender" => $allEmp->gender,
    "br_allow" => $allEmp->allowance,
    "work_days" => $working_days,
    "holiday_ot_hrs" => $holiday_ot_hrs,
    "holiday_ot_dys" => $holiday_ot_dys,
    "holiday_ot_amount" => $holiday_ot_amount
);

$sheet_data[1] = array(
    "employee_id" => $emp,
    "name" => $allEmp->name,
    "gender" => $allEmp->gender,
    "br_allow" => $allEmp->allowance,
    "work_days" => $working_days,
    "holiday_ot_hrs" => $holiday_ot_hrs,
    "holiday_ot_dys" => $holiday_ot_dys,
    "holiday_ot_amount" => $holiday_ot_amount
);

$sheet_data[2] = array(
    "employee_id" => $emp,
    "name" => $allEmp->name,
    "gender" => $allEmp->gender,
    "br_allow" => $allEmp->allowance,
    "work_days" => $working_days,
    "holiday_ot_hrs" => $holiday_ot_hrs,
    "holiday_ot_dys" => $holiday_ot_dys,
    "holiday_ot_amount" => $holiday_ot_amount
);

.
.
.
.
.
.

$sheet_data[50] = array(
        "employee_id" => $emp,
        "name" => $allEmp->name,
        "gender" => $allEmp->gender,
        "br_allow" => $allEmp->allowance,
        "work_days" => $working_days,
        "holiday_ot_hrs" => $holiday_ot_hrs,
        "holiday_ot_dys" => $holiday_ot_dys,
        "holiday_ot_amount" => $holiday_ot_amount
    );

现在将这些数组和表名传递给insert_batch函数。

$this->db->insert_batch('yourtable', $sheet_data); 
$this->db->insert_batch('mytable', $data);