update数组查询

uxhixvfz  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(345)

我正在使用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;
    }
}

但当我执行代码时,会有这样的消息

我知道我应该把参数转换成数组。但我不知道怎么做?谢谢你的帮助

e5nszbig

e5nszbig1#

希望这能帮助您:
你的 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-数据

相关问题