Search code examples
phpcodeigniternullcodeigniter-3cart

php CI $this->cart->insert($data) get null value


I get stack in script. I used Code Igniter ver. 3.1.10. I use cart library in my controller

here my controller

    public function add_to_cart()
        {
            $idit=$this->input->post('id_item');
            $product=$this->Salesmodel->get_item($idit);
            $i=$product->row_array();
            $data = array(
                   'id'             => $i['id_item'],
                   'name'           => $i['name_item'],
                   'main_price'     => $i['main_price'],
                   'sell_price'     => $i['sell_price'],

                );

            $this->cart->insert($data);
            $rows = count($this->cart->contents());    // I want to find out rows count and result is null
            echo $i['id_item'];                     //get value, not null
            echo $rows;                                // get '0'

        }

model.php

function get_item($idit)
{
   $rslt=$this->db->query("SELECT * FROM tb_item where id_item='$idit'");
   return $rslt;
}

but in that script i always get null row count of the cart. I have to add this script in config.php :

$config['sess_use_database'] = TRUE;

I also created a new table with a name

ci_session

but that returns the same result, my cart always has null row count and null data. Please help me with an error in the script that I made.

Thanks in advance


Solution

  • In order to save into the cart properly, these 4 array index are required :
    id - Item identifier.
    qty - Item quantity.
    price - Item price.
    name - Item name.

    And the 5th index are options, which you could store all the additional attribute you need (should be an array though).

    So you could modify the $data array like this :

            $data = array(
                   'id'             => $i['id_item'],
                   'qty'            => 1, // here I just manually set it to 1
                   'name'           => $i['name_item'],
                   'price'          => $i['main_price'], // here I changed 'main_price' index to 'price'
                   'options'        => array('sell_price' => $i['sell_price']) // moved the 'sell_price' array here
    
                );