Welcome Guest, Not a member yet? Register   Sign In
[SOLVED - Thank you] Extract Items from Cart->Contents() and insert into database
#1

[eluser]tkaw220[/eluser]
Hi,

I have a big headache with CI Cart. I would like insert all items from the $this->cart->contents()into my database. But my code below insert only the last entry and skip all previous entry.

$data = array();
foreach ($this->cart->contents() as $item)
{
$data = array(
'order_no' => $order_no,
'item' => $item['name'],
'qty' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}

How to fix my problem?

Billion thanks for help.

Thank you.
#2

[eluser]InsiteFX[/eluser]
Try this:
Code:
$data     = array();
$contents = array();

$contents = $this->cart->contents();

foreach ($contents as $key => $item)
{
   $data = array(
   ‘order_no’ => $order_no,
   ‘item’     => $item[‘name’],
   ‘qty’      => $item[‘qty’],
   ‘price’    => $item[‘price’],
   ‘subtotal’ => $item[‘subtotal’]
   );
}

InsiteFX
#3

[eluser]tkaw220[/eluser]
Hi InsiteFX,

Thank you for your tips. But your code returns error. I am still stuck at print out all items inside the cart() and insert them into database. Anyone has the solution?
#4

[eluser]Eric Barnes[/eluser]
I think this is what you want:
Code:
foreach ($this->cart->contents() as $item)
{
  $data = array(
  ‘order_no’ => $order_no,
  ‘item’ => $item[‘name’],
  ‘qty’ => $item[‘qty’],
  ‘price’ => $item[‘price’],
  ‘subtotal’ => $item[‘subtotal’]
  );
  $this->db->insert('table', $data);
}
#5

[eluser]tkaw220[/eluser]
Hi Eric Barnes,

Bingo. Billion thanks to both of you. Have a nice weekend.

By the way, let me share my finding with those who had encounter this situation.

I thought I encounter error with my initial script by using print_r to inspect the resulting array:

$data = array();

foreach ($this->cart->contents() as $item)
{
$data = array(
'order_no' => $order_no,
'item' => $item['name'],
'qty' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}

echo '<pre>';
print_r($data);

The output is the last item in the array. So I thought the previous items inside that array gone missing. In order to return proper result, add [] after the $data like this:

foreach ($this->cart->contents() as $item)
{
$data[] = array(
'order_no' => $order_no,
'item' => $item['name'],
'qty' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}

echo '<pre>';
print_r($data);

Now it output all items inside your array.

Thank you.

Best regards,
Edwin




Theme © iAndrew 2016 - Forum software by © MyBB