phpmysqlcodeignitersql-updatecodeigniter-query-builder

Binding array-type data to placeholders in a CodeIgniter query() renders an invalid query


I am making pharmacy system using Codeigniter. I want to update stock of several items in table after purchase, below is the code what i have tried so far.

Below is the my Controller

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);
}

And this is my Model:

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;
    }
}

But when I execute the code, there is a message like this enter image description here

I know I should turn parameter to array. But I don't know how?


Solution

  • Hope this will help you :

    Your update query should be in foreach loop since quantity and medicine both are an array. Should be like this :

    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');
    }
    

    For more : https://www.codeigniter.com/user_guide/database/query_builder.html#updating-data