Jump to content

loop INSERT statement with session variables


jrobles

Recommended Posts

I have a session that contains shopping cart data i.e

item#        qty            pricePerUnit

1                4              5.89

3                1              3.25

6                2              10.99

 

I want to insert these items into my table one item at a time but I cant figure out how to loop through the session variables.

 

Any suggestions?

THANKS IN ADVANCE

Link to comment
Share on other sites

Here is my var dump:

array(3) { ["cart"]=>  string(13) "3,3,3,3,2,2,4" ["ORDER_TOTAL"]=>  float(60.15) ["TOTAL_PROD"]=>  int(7) } 

 

"3333" means there are 4 of item # 3

"22" means there are 2 of item #2

 

Can I grab the price per unit by querying the product table within the loop before the insert statement?

Link to comment
Share on other sites

You can do whatever you want to do..

first you need to make iterate over the cart into something useable

 

if (isset($_SESSION['cart'])) {
$cart = array();
foreach (explode(',',$_SESSION['cart']) as $value) {
if (array_key_exists($value,$cart)) {
$cart[$value]['count']++;
} else {
$cart[$value] = array('count'=>1,'price'=>'');
}
}
}

this will give you an array that looks something like this..

 

Array(3){

[2] = >array(2) { ['count'] => 2, ['price'] =>'' },

[3] => array(2) { ['count'] => 4, ['price'] =>'' },

[4] => array(2) { ['count'] => 1, ['price'] =>'' }

}

 

then you just need to loop over that array grab the price for it and insert it into the database..

the above 'price' field may not be needed at all depending on how you do it..

 

Link to comment
Share on other sites

Your session data does not contain all the information needed per your original request. The session data only seems to contain the product IDs, the total cart price and the total cart quantity. It does not contain the price of each product. I suspect you could get the price per product from the database using the product IDs. In which case you do not need to add that to the cart information unless you are adding it for historical reasons (i.e. the price changes after the order was submitted and you need to know how much it sold for in that order)

 

But the manner in which you are storing the cart information requires additional processing to determine the quantity of each product. I would suggest changing how you are storing the session data. Do not store all the product IDs as a single string value separated by commas. Instead, I would store the cart data using the ID as the key and the quantity as the value. Something like this:

 

array(

    ["cart"]=>  array (
        [3] => 4,
        [2] => 2,
        [4] => 1,
    )
    ["ORDER_TOTAL"]=>  60.15,
    ["TOTAL_PROD"]=>  7
)

 

Also, why do you want to add each product individually to the database when you can add them all in one query. Example:

 

INSERT INTO table (cartID, productID, productQty, productCost)
VALUES (99, 3, 4, 3.33), (99, 2, 2, 2.22), (99, 4, 1, 4.44)

Link to comment
Share on other sites

Ok so now that you have made it into a nice and pretty array you can get the price (Do you really need to? cant you just link it up with the select query later?) you need to loop through the array and do all the magic.

 

$sql = "INSERT INTO `cart_table` (product, count) VALUES ";
$vals = array();
foreach ($cart as $id=>$var) {
$vals[] = '("'.$id.'","'.$var['count'].'")';
}
mysql_query($sql . join(',',$vals));

As long as you have a valid mysql connection..

This solution doesnt take into account adding the price. to the database..

Link to comment
Share on other sites

that didnt seem to work for me. This is what I have

 

//INSERT ORDER DETAIL RECORDS
if (isset($_SESSION['cart'])) {
$cart = array();
foreach (explode(',',$_SESSION['cart']) as $value) {
if (array_key_exists($value,$cart)) {
$cart[$value]['count']++;
} else {
$cart[$value] = array('count'=>1,'price'=>'');
}
}
}

$sql = "INSERT INTO `cart_table` (ProductID, QtyOrdered,OrderID) VALUES ";
$vals = array();
foreach ($cart as $id=>$var) {
$vals[] = '("'.$id.'","'.$var['count'].'","'.$OrderID.'")';
}
mysql_query($sql . join(',',$vals));
}

Link to comment
Share on other sites

No need to create a foreach loop to count all the values when you can do it with a single function call (although I would still recommend fixing the session data). I also noticed that the query is outside the IF procedure, so if no cart data exists in the session, the query is still run. This should do the same thing as above, but a little more efficiently:

 

<?php
//INSERT ORDER DETAIL RECORDS
if (isset($_SESSION['cart']))
{
    $cart = array_count_values($_SESSION['cart']);

    foreach ($cart as $id=>$var) {
        $vals[] = "('{$id}', '{$var['count']}', '{$OrderID}'";
    }

    $sql  = "INSERT INTO `cart_table` (ProductID, QtyOrdered,OrderID) VALUES " . implode(',', $vals);
    mysql_query($sql);
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.