How to insert multiple records to database in Code

2019-09-14 08:18发布

问题:

I want to insert some values to the database where i have got those values by doing some calculations.so right now i can view those values in a html report.but what i want to do is insert those multiple values to the database.there are 50 persons.so i want to add all the details of these 50 persons at same time by just clicking a button.how can i do this?what could be my controller view and model.

Here are the values that i get after the calculations in controller

$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
);

回答1:

you can create array like this for batch insert

$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); 

using batch insert you can insert multiple records for more details refer this link : https://www.codeigniter.com/userguide3/database/query_builder.html

Hope this will help you.



回答2:

First of all you have to create array for your records.

$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
    );

Now pass those array and table name to insert_batch function.

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