I used the $this->db->update();
function to update a field in a table using Codeigniter. I have the following model function to do this :
function addBills($fdata) {
if (!empty($fdata)) {
if ($this->db->affected_rows()) {
if ($this->db->update('store_update_stock', array('bill_status'=>'Added'),
array('update_stock_id' => $fdata['bill_id']))) {
return true;
}
}
}
return FALSE;
}
As an example, $fdata contains a bill_id, for example: 805 which matches with the update_stock_id in my table. Those values are outputting correctly, if used manually.
In the controller, I have:
if (!empty($files)) {
foreach ($files as $fname) {
$fdata[] = array(
'bill_id' => $this->input->post('bill'),
'file_name' => $fname,
'status' => 1
);
}
$this->Item_model->addBills($fdata);
}
I want to update the bill_status as "Added" when matching the update_stock_id in the table.
There is no update of the table
Why is the table not updating, when using variable data?
you are calling $this->db->affected_rows()
before you do the update and therefore returning always false
. You need to change the order of functions like this:
function addBills($fdata) {
if (!empty($fdata)) {
$this->db->update('store_update_stock', array('bill_status'=>'Added'), array('update_stock_id' => $fdata['bill_id']));
if ($this->db->affected_rows()) {
return true;
}
else {
return FALSE;
}
}
}
see: affected_rows() and Updating Data
If I change the code as you suggest, I get no output. If I use
array('update_stock_id' => 805')
hard coded, the update is working fine.
This is because your array is returned indexed. Your controller function has a foreach loop, within it has an array, which gets indexed:
foreach ($files as $fname) {
$fdata[] = array(...);
}
Since you are expecting just one bill_id, you use the first (zero indexed array element):
array('update_stock_id' => $fdata[0]['bill_id']))