2
votes

I want update several row from database table with foreach but give following error:

This is my php code:

$id_units       = $this->input->post('id_units');
$name_un       = $this->input->post('name_units');      
$price_un        = $this->input->post('price_units');
$description_un = $this->input->post('explanation_units');
$ex_un       = $this->input->post('addition_units');
$service_un        = $this->input->post('checkbox_units');
$data2 = array();
foreach ($name_un as $idx => $name) {
    $data2 = array(
        'relation' => $id_residence,
        'name_un' => $name_un[$idx],
        'price_un' => $price_un[$idx],
        'description_un' => $description_un[$idx],
        'ex_un' => $ex_un[$idx],
        'service_un' => json_encode($service_un[$idx]), // This Is Line Number: 212
    );
$this->db->update('hotel_units', $data2, array('id' => $id_units[$idx]));
};

Above code have this error:

A Database Error Occurred
Error Number: 1054
Unknown column 'Array' in 'where clause'
UPDATE hotel_units SET 0 = Array WHERE id = Array
Filename: D:\xampp\htdocs\system\database\DB_driver.php
Line Number: 330

Update:

I have new error:

A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: residence.php
Line Number: 212

A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 2
Filename: residence.php
Line Number: 212

A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 3
Filename: residence.php
Line Number: 212

'service_un' =>... are checkbox. See Line Number: 212 in above php code

1

1 Answers

1
votes

Looks like $id_units is an array of values.

You could try with this code, but it assumes that, like the rest of your input fields, id is also an array and has the same index of the others. You didn't provide your html form so I'm just guessing....Anyway, the last param of $this->db->where() needs to be a single value, even if you write it as an array (but of one element).

$id_units       = $this->input->post('id_units');
$name_un       = $this->input->post('name_units');      
$price_un        = $this->input->post('price_units');
$description_un = $this->input->post('explanation_units');
$ex_un       = $this->input->post('addition_units');
$service_un        = $this->input->post('checkbox_units');
$data2 = array();
foreach ($name_un as $idx => $name) {
    $data2 = array(
        'relation' => $id_residence,  // Or is it $id_residence[$idx] ?
        'name_un' => $name_un[$idx],
        'price_un' => $price_un[$idx],
        'description_un' => $description_un[$idx],
        'ex_un' => $ex_un[$idx],
        'service_un' => json_encode($service_un[$idx]),
    );
   $this->db->update('hotel_units', $data2, array('id' => $id_units[$idx]));
};