php - How do i update multiple rows with multiple condition in Code Igniter -
i learning php , using codeigniter
framework. i'm using code in controller when inserting new data , it's working.
//insert multi rows tabel harga_inventori $kode_inventori = $_post['kode_inventori']; $result = array(); foreach($_post['kode_kategori_pelanggan'] $key => $val){ $result[] = array( "kode_kategori_pelanggan" => $_post['kode_kategori_pelanggan'][$key], "kode_inventori"=>$kode_inventori, "harga" => $_post['harga_jual'][$key], "diskon" => $_post['diskon'][$key] ); } $res = $this->db->insert_batch('harga_inventori', $result); redirect("inventori");
but when i'm using same pattern updating function, it's not working @ all.
for($i = 0; $i < count($_post['harga_jual'][$i]); $i++) { if($_post['kode_kategori_pelanggan'][$i] != '') { $res[] = array( 'harga' => $_post['harga_jual'][$i], 'diskon' => $_post['diskon'][$i], ); $this->db->where('kode_inventori',$_post['kode_inventori']); $this->db->where('kode_kategori_pelanggan',$_post['kode_kategori_pelanggan'][$i]); $this->db->update('harga_inventori',$res); } } redirect("inventori");
i'm trying update_batch()
got many errors, i'm using for
loop , updating single row @ time.
what problem here?
its typo. should pass array $res
not $data
, , change $res[]
$res
since not needed. should check isset()
prevent errors of undefined:
for($i = 0; $i < count($_post['harga_jual'][$i]); $i++) { if(isset($_post['kode_kategori_pelanggan'][$i])) { $res = array( 'harga' => $_post['harga_jual'][$i], 'diskon' => $_post['diskon'][$i], ); $this->db->where('kode_inventori',$_post['kode_inventori']); $this->db->where('kode_kategori_pelanggan',$_post['kode_kategori_pelanggan'][$i]); $this->db->update('harga_inventori',$res); } } redirect("inventori");
it see of data know trying do. seems little strange initiate counter $i
@ same time using array key in loop this: for($i = 0; $i < count($_post['harga_jual'][$i]); $i++)
it know how data in $_post
looks like. try remove [$i]
in loop. check each post variable set before using them, like:
for($i = 0; $i < count($_post['harga_jual']); $i++) { if(isset($_post['kode_kategori_pelanggan'][$i])) { // check if post variables set , if not set default value (in example empty string): $harga_jual = isset($_post['harga_jual'][$i]) ? $_post['harga_jual'][$i] : ''; $diskon = isset($_post['diskon'][$i]) ? $_post['diskon'][$i] : ''; $kode_inventori = isset($_post['kode_inventori']) ? $_post['kode_inventori'] : ''; $kode_kategori_pelanggan = $_post['kode_kategori_pelanggan'][$i]; // checked isset above... $data = array( 'harga' => $harga_jual, 'diskon' => $diskon, ); $this->db->where('kode_inventori',$kode_inventori); $this->db->where('kode_kategori_pelanggan', $kode_kategori_pelanggan); $this->db->update('harga_inventori', $data); } } redirect("inventori");
Comments
Post a Comment