How to insert user_id (from DB) and imported data (excel file upload) simultaneously?

59 Views Asked by At

Table (expected result)

id teacher_id subject student_id marks section_id
1 23 math 200 70 7
2 23 math 201 73 7
3 23 math 202 72 7
4 23 math 203 76 7
5 23 math 204 78 7
6 23 math 205 80 7

I am importing students marks using Simplexlsx.class.php into database in CodeIgniter 3. I need to import the data from excel uploaded file (contains only rows of student's marks and teacher notes in the excel template), meanwhile I want the student_id (collected from DB) to be inserted into the table simultaneously.

QUERY to get student_id:

$section = $this->input->post('section-id');
$query_data_student = $this->db->select('student_id')->from('student')->where('section_id', $section)->order_by('name', 'ASC')->get()->result_array();

Looping and inserting from excel upload

foreach( $xlsx->rows() as $r ) {
// Ignore the inital name row of excel file
if ($f == 0){ 
$f++;
continue;}
/**NOT really sure this foreach loop will work**/
foreach($query_data_student as $rows){
   $arr_student_id = $rows['student_id'];
}
        
for( $i=2; $i < $num_cols; $i++ ){ 
   if ($i == 2) $data['marks']         = $r[$i];
   else if ($i == 3)    $data['notes'] = $r[$i];
}
$data['student_id'] = '200'; //have tried to place $arr_student_id;  **//Here is the problem (I want this value [student_id] inserted from student table)**
$data['subject_name']   = $this->input->post('subject');
$data['teacher_id'] = $this->input->post('teacher_id');
$this->studentMarking_model->save($data);
}

Using the above code I get the following table in my DB:

Table (current result)

id teacher_id subject student_id marks section_id
1 23 math 200 70 7
2 23 math 200 73 7
3 23 math 200 72 7
4 23 math 200 76 7
5 23 math 200 78 7
6 23 math 200 80 7

I don't really cope with array data handling. Many thanks for any kind help.

1

There are 1 best solutions below

0
harmoni creative On

After implementing what @CBroe suggest, I solve the problem. This is my first foreach:

foreach($query_data_student as $rows){ $arr_student_id[$rows['student_matrix']] = $rows['student_id']; /*I select student's metric numbers instead of students' name (this to avoid , just in case, there are exactly same student's names. Indeed, I found it during my school age).*/ }

Then I iterate through for loop:

for( $i=2; $i < $num_cols; $i++ ){ if ($i == 2) $data['student_id'] = $arr_student_id[$r[$i]]; //here I get the CSV column of metric numbers after modifying the template else if($i == 3) $data['marks'] = $r[$i]; else if ($i == 4) $data['notes'] = $r[$i]; }

Thanks @cbroe for your extraordinary help.