Updating Batch Model by ID Codeigniter

Viewed 62

I'm trying to batch update a table by an ID

Here's my model

  public function update_batch_studentextend_by_studentID($data, $id = NULL) {
   $this->db->update_batch($this->_table_name, $data, "studentID => $id");
    return $id;
}

But it shows this error

A Database Error Occurred
One or more rows submitted for batch updating is missing the specified index.
Filename: models/Studentextend_m.php
Line Number: 41

Controller:

        $post = $this->input->post();
                        for($i=0; $i < count($post['subject']); $i++) {
                            $studentExtendArray[] = array(
                                'studentID' => $studentID,
                                'subject' => $post['subject'][$i],
                                'subjectng' => $post['subjectng'][$i],
                                'subjectlg' => $post['subjectlg'][$i],
                                'subjectcre' => $post['subjectcre'][$i],
    
    
                            );
                                $this->db->update_batch('studentextend', $studentExtendArray, 'studentID');

Array output:

Array (
[0] => Array
    (
        [studentID] => 97
        [subject] => 
        [subjectng] => 115
        [subjectlg] => A+
        [subjectcre] => 7.0
    )

[1] => Array
    (
        [studentID] => 97
        [subject] => 
        [subjectng] => 110
        [subjectlg] => B-
        [subjectcre] => 7.0
    )

[2] => Array
    (
        [studentID] => 97
        [subject] => 
        [subjectng] => 90
        [subjectlg] => C-
        [subjectcre] => 8.0
    ) )

What i'm trying to do is update multiple rows with respect of "studentID" column.

The array output is correct, different values for each row, except for the StudentID, because that's what im trying to update the info on. But in the table, it shows same values for the 3 arrays/rows.

1 Answers
<?php

$data = array(
    array(
        'id' => 1,
        'name' => 'Scott',
        'age' => 25,
        'created_at' => date('Y-m-d H:i:s')
    ),
    array(
        'id' => 2,
        'name' => 'Tom',
        'age' => 30,
        'created_at' => date('Y-m-d H:i:s')
    )
);

$this->db->update_batch('students', $data, 'id'); ?>

So your function does not need to pass in an id as it's in the $data, therefore if it all works, you can just get the ids from the $data as you already have them.

Related