我正在使用Codeigniter制作药房系统。我想在购买后更新表中几项的库存,以下是到目前为止我尝试过的代码。
下面是我的控制器
function add_invoice(){
$customer = $this->input->post('customer');
$date = date("Y-m-d",strtotime($this->input->post('date')));
$grandtotal = $this->input->post('grandtotal');
$ref = rand(1111111111,9999999999);
$medicine = $this->input->post('medicine');
$quantity = $this->input->post('quantity');
$subtotal = $this->input->post('subtotal');
foreach($medicine as $key=>$val){
$data[] = array(
'customer' => $customer,
'date' => $date,
'grandtotal' => $grandtotal,
'ref' => $ref,
'medicine' => $val,
'quantity' => $quantity[$key],
'subtotal' => $subtotal[$key],
);
}
$this->my_model->decrement_item($medicine, $quantity);
$this->db->insert_batch('table_invoice', $data);
}
这是我的下面的模型:
function decrement_item($medicine, $quantity)
{
$q = "UPDATE table_med SET stock = stock - ? WHERE medicine = ?";
$this->db->query($q, [$quantity, $medicine]);
if($this->db->affected_rows() > 0){
return TRUE;
}
else{
return FALSE;
}
}
我知道我应该将参数转换为数组。但是我不知道怎么办?谢谢您的帮助
答案 0 :(得分:1)
希望这对您有帮助:
您的update
查询应该在foreach
循环中,因为quantity
和medicine
都是一个数组。应该是这样的:
foreach($medicine as $key=>$val)
{
$data[] = array(
'customer' => $customer,
'date' => $date,
'grandtotal' => $grandtotal,
'ref' => $ref,
'medicine' => $val,
'quantity' => $quantity[$key],
'subtotal' => $subtotal[$key],
);
$this->db->set('stock', 'stock-'.$quantity[$key], FALSE);
$this->db->where('medicine', $val);
/* if not works use this
$this->db->where('medicine', $medicine[$key]);
*/
$updated = $this->db->update('table_med');
}
更多信息:https://www.codeigniter.com/user_guide/database/query_builder.html#updating-data