Page 1 of 1

Please help me fix this puzzling shopping cart problem

Posted: Thu Aug 07, 2008 8:00 pm
by <br>
Please help me find the problem here... I am trying to add sizing into this shopping cart and the session variables are getting mixed up with one another.

http://webdesign.nfshost.com/TShirts/ - here is where you can test the cart out (add/delete tqtqtq & afafa with various sizing options)

Try adding/deleting items for a while and watch the anomalies... size options for afafa will transfer over to tqtqtq's session variable... sometimes it may seem like its working for a while, but keep trying and it will screw up... Also, when you delete an item from the cart, sometimes the other item's size options will disappear. They will even reappear sometimes if I'm not mistaken.

Thanks

Code: Select all

<?php
session_start();
$action=$_GET['action'];
$rem=$_GET['rem'];
$cart = $_SESSION['cart'];
 
 
if ($action == 'add_item'){
$itemsize=$_POST['options'];
$cart = $_SESSION['cart'];
if ($cart!='' && $cart!=' ') {
$cart .= ','.$_GET['id'];
} else {
$cart = $_GET['id'];
}
$_SESSION['cart'] = $cart;
}
 
if ($rem=='del'){
$id=$_GET['id'];
$eggyolkB='count-'.$id;
$thec=$_SESSION[$eggyolkB];
$finale='rowopt'.$thec;
 
$_SESSION[$finale]='';
 
if ($cart==$id){
$cart='';
$_SESSION['cart'] = $cart;
}
 
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
 
 
if ($id != $item) {
if ($newcart != '') {
$newcart .= ','.$item;
} else {
$newcart = $item;
}
}
}
$cart = $newcart;
}
 
}
 
if ($action == 'update'){
 
 
    if ($cart) {
        $newcart = '';
        foreach ($_POST as $key=>$value) {
            if (stristr($key,'qty')) {
                $id = str_replace('qty','',$key);
                $lenlen = strlen($value);
                if ($lenlen!=0 && strspn($value,"1234567890")!=$lenlen){
                $death='death';
                        }
                    }
                }
if ($death!='death'){
 
        foreach ($_POST as $key=>$value) {
            if (stristr($key,'qty')) {
                $id = str_replace('qty','',$key);
                $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
                $newcart = '';
                foreach ($items as $item) {
                    if ($id != $item) {
                        if ($newcart != '') {
                            $newcart .= ','.$item;
                        } else {
                            $newcart = $item;
                        }
                    }
                }
                for ($i=1;$i<=$value;$i++) {
                    if ($newcart != '') {
                        $newcart .= ','.$id;
                    } else {
                        $newcart = $id;
                    }
                }
            }
        }
$cart = $newcart;
}
}
}
 
if ($death!='death'){
 
$_SESSION['cart'] = $cart;
 
$column==1;
 
 
$items = explode(',',$cart,100);
//array of all items in cart
$_SESSION[num_items] =count($items);
$inlist = implode(", ",$items);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$_SESSION[unique_items] =count($contents);
 
$vivian=1;
if($_SESSION[cart] != ''){
$db = 'XXXXXX.db';
$user = 'XXXXXX';
$pass = 'XXXXXX';
$db2 = 'items';
$table = 'items';
$select = '*';
$con = mysql_connect($db, $user, $pass) or die(mysql_error());
mysql_select_db($db2) or die(mysql_error());
$query  = "SELECT $select FROM $table WHERE id IN ($inlist)";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$beeb=$row[image75];
$_SESSION[rowMT.$vivian]=$beeb;
$p=$row[id];
$_SESSION[rowid.$vivian]=$p;
$caddy=$row[cat1];
$caddylnk=explode(' - ',$caddy,100);
$cc1=$caddylnk[0];
$cc2=$caddylnk[1];
$_SESSION[rowlnk.$vivian]= $_SESSION[backbutton].'?id='.$p;
$ebbe=$row[name];
$_SESSION[rowname.$vivian]=$ebbe;
$q=$contents[$p];
$_SESSION[rowquant.$vivian]=$q;
$c=$row['price'];
$_SESSION[rowprice.$vivian]=$c;
$_SESSION[rowsum.$vivian] =($c*$q);
$tippity=$_GET['id'];
 
if ($tippity==$p && isset($itemsize)){
 
if (empty($_SESSION[rowopt.$vivian]) || $_SESSION[rowopt.$vivian]==''){
$boz='skaggs';
} else {
$boz='';
}
 
if ($boz != 'skaggs'){
$_SESSION[rowopt.$vivian]=$_SESSION[rowopt.$vivian].', '.$itemsize;
} else if ($boz=='skaggs') {
$_SESSION[rowopt.$vivian]=$itemsize;
}
}
$vivian++;
}
$ttt=1;
$additives = array();
while ( $ttt <= $_SESSION[unique_items] ){
$additives[$ttt] = $_SESSION[rowsum.$ttt];
$ttt++;
$_SESSION[total]=array_sum($additives);
}
}else{
$_SESSION[total]=0;
$_SESSION[num_items]=0;
 
}
if($_SESSION['cart']==''){
$_SESSION[unique_items]=0;
}
$_SESSION['cart'] = $cart;
if (isset($rem) || $action=='update'){
header("location:http://www.JReidyWebDesign.com/shoppingcart");
} else {
$backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback];
if(isset($_SESSION[gobackid])){
$backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback].'?id='.$_SESSION[gobackid];
}
 
header("location: $backbackback");
}
} else {
header("location:http://www.JReidyWebDesign.com/shoppingcart?qtyerror=23");
}
?>

Re: Please help me fix this puzzling shopping cart problem

Posted: Thu Aug 07, 2008 11:05 pm
by Christopher
That's a lot of code. Do you have some idea where things are going wrong?

Re: Please help me fix this puzzling shopping cart problem

Posted: Fri Aug 08, 2008 12:40 am
by Stryks
Wow ... that is going to take some fixing.

It's a little eaiser to read when it's fully indented.

Code: Select all

<?php
    session_start();
 
    $action=$_GET['action'];
    $rem=$_GET['rem'];
    $cart = $_SESSION['cart'];
     
    if ($action == 'add_item'){
        $itemsize=$_POST['options'];
        $cart = $_SESSION['cart'];
        if ($cart != '' && $cart != ' ') {
            $cart .= ',' . $_GET['id'];
        } else {
            $cart = $_GET['id'];
        }
        $_SESSION['cart'] = $cart;
    }
     
    if ($rem=='del'){
        $id=$_GET['id'];
        $eggyolkB='count-'.$id;
        $thec=$_SESSION[$eggyolkB];
        $finale='rowopt'.$thec;
     
        $_SESSION[$finale]='';
     
        if ($cart==$id){
            $cart='';
            $_SESSION['cart'] = $cart;
        }
     
        if ($cart) {
            $items = explode(',',$cart);
            $newcart = '';
            foreach ($items as $item) {
     
     
                if ($id != $item) {
                    if ($newcart != '') {
                    $newcart .= ','.$item;
                    } else {
                    $newcart = $item;
                    }
                }
            }
            $cart = $newcart;
        }
     
    }
     
    if ($action == 'update'){
     
     
        if ($cart) {
            $newcart = '';
            foreach ($_POST as $key=>$value) {
                if (stristr($key,'qty')) {
                    $id = str_replace('qty','',$key);
                    $lenlen = strlen($value);
                    if ($lenlen!=0 && strspn($value,"1234567890")!=$lenlen){
                        $death='death';
                    }
                }
            }
            
            if ($death!='death'){
     
                foreach ($_POST as $key=>$value) {
                    if (stristr($key,'qty')) {
                        $id = str_replace('qty','',$key);
                        $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
                        $newcart = '';
                        foreach ($items as $item) {
                            if ($id != $item) {
                                if ($newcart != '') {
                                    $newcart .= ','.$item;
                                } else {
                                    $newcart = $item;
                                }
                            }
                        }
                        for ($i=1;$i<=$value;$i++) {
                            if ($newcart != '') {
                                $newcart .= ','.$id;
                            } else {
                                $newcart = $id;
                            }
                        }
                    }
                }
                $cart = $newcart;
            }
        }
    }
     
    if ($death!='death'){
     
        $_SESSION['cart'] = $cart;
         
        $column==1;
         
         
        $items = explode(',',$cart,100);
        //array of all items in cart
        $_SESSION[num_items] =count($items);
        $inlist = implode(", ",$items);                                                         
        $contents = array();
        foreach ($items as $item) {
        $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
        }
        $_SESSION[unique_items] =count($contents);
         
        $vivian=1;
        if($_SESSION[cart] != ''){
            $db = 'XXXXXX.db';
            $user = 'XXXXXX';
            $pass = 'XXXXXX';
            $db2 = 'items';
            $table = 'items';
            $select = '*';
            $con = mysql_connect($db, $user, $pass) or die(mysql_error());
            mysql_select_db($db2) or die(mysql_error());
            $query  = "SELECT $select FROM $table WHERE id IN ($inlist)";
            $result = mysql_query($query) or die(mysql_error());
            while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $beeb=$row[image75];
                $_SESSION[rowMT.$vivian]=$beeb;
                $p=$row[id];
                $_SESSION[rowid.$vivian]=$p;
                $caddy=$row[cat1];
                $caddylnk=explode(' - ',$caddy,100);
                $cc1=$caddylnk[0];
                $cc2=$caddylnk[1];
                $_SESSION[rowlnk.$vivian]= $_SESSION[backbutton].'?id='.$p;
                $ebbe=$row[name];
                $_SESSION[rowname.$vivian]=$ebbe;
                $q=$contents[$p];
                $_SESSION[rowquant.$vivian]=$q;
                $c=$row['price'];
                $_SESSION[rowprice.$vivian]=$c;
                $_SESSION[rowsum.$vivian] =($c*$q);
                $tippity=$_GET['id'];
             
                if ($tippity==$p && isset($itemsize)){
             
                    if (empty($_SESSION[rowopt.$vivian]) || $_SESSION[rowopt.$vivian]==''){
                        $boz='skaggs';
                    } else {
                        $boz='';
                    }
                 
                    if ($boz != 'skaggs'){
                        $_SESSION[rowopt.$vivian]=$_SESSION[rowopt.$vivian].', '.$itemsize;
                    } else if ($boz=='skaggs') {
                        $_SESSION[rowopt.$vivian]=$itemsize;
                    }
                }
                $vivian++;
            }
            $ttt=1;
            $additives = array();
            while ( $ttt <= $_SESSION[unique_items] ){
                $additives[$ttt] = $_SESSION[rowsum.$ttt];
                $ttt++;
                $_SESSION[total]=array_sum($additives);
            }
        } else {
            $_SESSION[total]=0;
            $_SESSION[num_items]=0;
        }
        if($_SESSION['cart']==''){
            $_SESSION[unique_items]=0;
        }
        $_SESSION['cart'] = $cart;
        if (isset($rem) || $action=='update'){
            header("location:http://www.JReidyWebDesign.com/shoppingcart");
        } else {
            $backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback];
            if(isset($_SESSION[gobackid])){
                $backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback].'?id='.$_SESSION[gobackid];
            }
         
            header("location: $backbackback");
        }
    } else {
        header("location:http://www.JReidyWebDesign.com/shoppingcart?qtyerror=23");
    }
?>
Now ... trying to read though this, the first thing that pops out at me is the use for cute variable names. Well .. they probably seemed cute when you did it ... but in 6 or 12 months time when you look at this code you will be where I am right now ... "What the ... ? Where is that set and why?". When you're setting flags, try and make them descriptive, and where possible, re-use them. And, yeah ... just try to keep them to a minimum.

An example of this (though in a different aspect) is the $_GET variables you are using. You seem to be using $_GET['action'] for add and edit, but $_GET['rem'] for delete? Why not the one for all actions. Surely $_GET['action'] describes the content of the variable much better? And what is with all the re-labeling of variables?

Code: Select all

if($_POST['action'] = 'add_item') // ... take action
 
// is so much easier to understand than ..
 
$gerbil_feet = $_POST['action'];
// big wad of code
if($gerbil_feet == 'add_item') { // ... take action
 
I see the logic ... it makes it smaller and easier to type, yes? But it makes it SOOOOO much harder to read. If you're working with a $_POST variable ... then access it via $_POST. Renaming it is redundant and confusing, and worse, it can lead you to forget that it IS and post variable and SHOULD NOT BE TRUSTED. You have NO security in place by the way .. we'll have to work on that a little later.

I'm also wondering why you are using javascript to submit a cart add when an image button could be used. Do you realize that non-javascript users may not be able to add anything to their cart? On javascript, I hope that javascript validation code isn't the only validation that your site uses. You should *always* use server side validation (PHP).

Next ... I have been looking through but I'm having trouble following the logic. I cant seem to find where the size options are added to the cart at all. Perhaps they aren't. I'd suggest you restructure the way you store the items in $_SESSION.

For example ...

Code: Select all

<?php
    session_start();
 
    // VALIDATE THINGS THAT WILL BE STORED(database / sessions) OR DISPLAYED
    if(!is_numeric($_GET['id'])) {
        echo 'Validation failed - trigger error handling method';
        exit();
    }
    if(isset($_POST['options'])) {
        if(!ctype_alnum($_POST['options'])){
        echo 'Validation failed - trigger error handling method';
        exit();        
        }
    }   
  
    if ($_GET['action'] == 'add_item') {     
        // If the ID added is present in the cart and it is of the same size ...
        if(isset($_SESSION['cart'][$_GET['id']]) && ($_SESSION['cart'][$_GET['id']]['size'] == $_POST['options'])) {
            // ... increase the current item qty by 1
            $_SESSION['cart'][$_GET['id']]['qty']++ ;
        } else {
            // ... otherwise we need to add this new item to the cart
            $_SESSION['cart'][$_GET['id']] = array('qty' => 1, 'size' => $_POST['options']);;
        }
    }
?>
 
So now, you have your data all wrapped up in a nice little multidimensional array. No need for exploding or imploding, or for keeping parallel arrays storing what the item is and what the options are.

Of course, you'd want to add a section to pull the item name and cost from the database and add that to the session as well. Makes it easy to display and calculate cart cost and item count.

As an example ...

Code: Select all

   // How many items are in the cart?
    $cart_count = 0;
    if(isset($_SESSION['cart'])) {
        foreach($_SESSION['cart'] as $item_id => $item_data) $cart_count += $item_data['qty']; 
    }
This isn't really a solution to your problem, I know. But it's the easiest way I can think of to pull your cart into a state where cart data will be stored in a logical way and is less vulnerable to the kind of problems you are getting.

I'm happy to help you develop this further if you're keen to clean that code up.

Cheers

Re: Please help me fix this puzzling shopping cart problem

Posted: Fri Aug 08, 2008 10:45 am
by <br>
Thanks for the great post.

This code is a lot nicer... I usually just code in non-indented lines using notepad, but it's nice to be able to follow the brackets without counting...

Listed below is cart.php and the code for the external shopping cart... the problem lies with ordering, item id... tqtqtq has a lower id than afafa, so when you add one (and an afafa is already in the cart) is take's afafa's spot & attributes somewhere along the way. Any ideas?

As far as security goes, the most valuable thing we're going to store here is customer emails in a MySQL database... going to implement paypal website payments standard with cart upload (so people don't go to paypal's site until they hit proceed to checkout) so I won't have anything worth stealing data-wise. Keeping that in mind, what security should I implement?

Code: Select all

<?php
session_start();
$cart = $_SESSION['cart'];
 
 
if ($_GET['action'] == 'add_item'){
    $itemsize=$_POST['options'];
    $cart = $_SESSION['cart'];
        if ($cart!='' && $cart!=' ') {
        $cart .= ','.$_GET['id'];
        } else {
        $cart = $_GET['id'];
        }
    $_SESSION['cart'] = $cart;
}
 
 
 
if ($_GET['action']=='delete'){
    $id=$_GET['id'];
    $eggyolkB='count-'.$id;
    $thec=$_SESSION[$eggyolkB];
    $finale='rowopt'.$thec;
 
    $_SESSION[$finale]='';
 
        if ($cart==$id){
            $cart='';
            $_SESSION['cart'] = $cart;
        }
 
        if ($cart) {
        $items = explode(',',$cart);
        $newcart = '';
            foreach ($items as $item) {
 
                if ($id != $item) {
                    if ($newcart != '') {
                    $newcart .= ','.$item;
                    } else {
                    $newcart = $item;
                    }
                }
            }
        $cart = $newcart;
    }
 
}
 
 
if ($_GET['action'] == 'update'){
 
 
    if ($cart) {
        $newcart = '';
        foreach ($_POST as $key=>$value) {
            if (stristr($key,'qty')) {
                $id = str_replace('qty','',$key);
                $lenlen = strlen($value);
                if ($lenlen!=0 && strspn($value,"1234567890")!=$lenlen){
                $quantchar='error';
                        }
                    }
                }
if ($quantchar!='error'){
 
        foreach ($_POST as $key=>$value) {
            if (stristr($key,'qty')) {
                $id = str_replace('qty','',$key);
                $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
                $newcart = '';
                foreach ($items as $item) {
                    if ($id != $item) {
                        if ($newcart != '') {
                            $newcart .= ','.$item;
                        } else {
                            $newcart = $item;
                        }
                    }
                }
                for ($i=1;$i<=$value;$i++) {
                    if ($newcart != '') {
                        $newcart .= ','.$id;
                    } else {
                        $newcart = $id;
                    }
                }
            }
        }
$cart = $newcart;
}
}
}
 
 
if ($quantchar!='error'){
 
    $_SESSION['cart'] = $cart;
    $column==1;
 
 
    $items = explode(',',$cart,100);
    //array of all items in cart
    $_SESSION[num_items] =count($items);
    $inlist = implode(", ",$items);
    $contents = array();
    foreach ($items as $item) {
        $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
        }
    $_SESSION[unique_items] =count($contents);
 
 
    if($_SESSION[cart] != ''){
 
        $con = mysql_connect('XXXX.db', 'XXXX', 'XXXX') or die(mysql_error());
        mysql_select_db('items') or die(mysql_error());
        $query  = "SELECT * FROM items WHERE id IN ($inlist)";
        $result = mysql_query($query) or die(mysql_error());
        $cart_counter=1;
        while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $_SESSION[rowMT.$cart_counter]=$row[image75];
            $_SESSION[rowid.$cart_counter]=$row[id];
            $caddy=$row[cat1];
            $caddylnk=explode(' - ',$caddy,100);
            $cc1=$caddylnk[0];
            $cc2=$caddylnk[1];
            $_SESSION[rowlnk.$cart_counter]= $row[cat1].'?id='.$row[id];
            $_SESSION[rowname.$cart_counter]=$row[name];
            $_SESSION[rowquant.$cart_counter]=$contents[$row[id]];
            $_SESSION[rowprice.$cart_counter]=$row['price'];
            $_SESSION[rowsum.$cart_counter] =($_SESSION[rowprice.$cart_counter]*$_SESSION[rowquant.$cart_counter]);
 
            if ($row[id]==$_GET['id'] && isset($itemsize)){
 
                if (empty($_SESSION[rowopt.$cart_counter]) || $_SESSION[rowopt.$cart_counter]==''){
                    $option_empt='empty';
                    } else {
                    $option_empt='';
                    }
 
                if ($option_empt != 'empty'){
                    $_SESSION[rowopt.$cart_counter]=$_SESSION[rowopt.$cart_counter].', '.$itemsize;
                    } else if ($option_empt == 'empty') {
                    $_SESSION[rowopt.$cart_counter]=$itemsize;
                    }
                }
            $cart_counter++;
            }
        $cart_counterB=1;
        $additives = array();
        while ( $cart_counterB <= $_SESSION[unique_items] ){
            $additives[$cart_counterB] = $_SESSION[rowsum.$cart_counterB];
            $cart_counterB++;
            $_SESSION[total]=array_sum($additives);
            }
        }else{
        $_SESSION[total]=0;
        $_SESSION[num_items]=0;
        }
 
    if($_SESSION['cart']==''){
        $_SESSION[unique_items]=0;
        }
    $_SESSION['cart'] = $cart;
    if ($_GET['action']=='delete' || $_GET['action']=='update'){
        header("location:http://www.JReidyWebDesign.com/shoppingcart");
        } else {
        $backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback];
        if(isset($_SESSION[gobackid])){
            $backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback].'?id='.$_SESSION[gobackid];
            }
        header("location: $backbackback");
        }
    } else {
    header("location:http://www.JReidyWebDesign.com/shoppingcart?qtyerror=23");
    }
?>

Code: Select all

if ($exploded_url[1] == 'shoppingcart') {
    $qtyerror=$_GET[qtyerror];
    $_SESSION[goback]=$backbuttonurl;
    $_SESSION[gobackid]=$backbuttonid;
 
    echo '<Table width=655 cellspacing=0 cellspadding=0><TR><TD style="padding-bottom: 10px" align=left nowrap><p class="mainheader">Your Shopping Cart</p></TD><TD style="padding-left: 35px;padding-bottom: 10px" width="100%"><a style="font-size: 9pt; color: rgb(153, 153, 153);" href="';
    $backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback];
    if(isset($_SESSION[gobackid])){
        $backbackback='http://www.jreidywebdesign.com'.$_SESSION[goback].'?id='.$_SESSION[gobackid];
    }
    echo $backbackback.'">< <strong>back to shopping</strong></a></TD></TR></Table>';
    if($cart==''){
        $_SESSION[unique_items]=0;
    }
    echo '<Table width=655 cellspacing=0 cellspadding=0><form action="cart.php?action=update" method="post" id="cart" STYLE="margin: 0px; padding: 0px;"><TR><TD align=center width=75> </TD><TD width=125 align=center><u><span style="color: #ffffff; font-weight: bold; ">Item</span></u></TD><TD width=125 align=center><u><span style="color: #ffffff; font-weight: bold; ">Price</span></u></TD><TD width=100 align=center><u><span style="color: #ffffff; font-weight: bold; ">Quantity</span></u></TD><TD width=130 align=center><u><span style="color: #ffffff; font-weight: bold; ">Total</span></u></TD><TD width=125 align=center><u><span style="color: #ffffff; font-weight: bold; ">Remove</span></u></TD><TD width=205></TD></TR>';
    $countess=1;
    while ( $countess <= $_SESSION[unique_items] ){
        echo '<TR><TD align=left style="padding-bottom: 10px; "><a href="';
        echo $_SESSION[rowlnk.$countess];
        echo '" target="_BLANK"><image src="/image/';
        echo $_SESSION[rowMT.$countess];
        echo '" border=0></a></TD><TD class="txt14b" align=center style="padding-left:15px"><span style="color: #ffffff; font-weight: bold; ">';
        echo $_SESSION[rowname.$countess];
        echo ' ('.$_SESSION[rowopt.$countess].')</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; ">$';
        echo $_SESSION[rowprice.$countess];
        echo '</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; "><input type=text name="qty'.$_SESSION[rowid.$countess].'" id="quant" MAXLENGTH=2 VALUE="';
        echo $_SESSION[rowquant.$countess];
        echo '" SIZE=2>';
        $egg=$_SESSION[rowid.$countess];
        $eggyolk='count-'.$egg;
        $_SESSION[$eggyolk]=$countess;
        echo '</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; ">$';
        echo $_SESSION[rowsum.$countess];
        echo '</span></TD><TD class="txt14b" align=center><a href="cart.php?action=delete&id=';
        echo $_SESSION[rowid.$countess];
        echo '">'.$egg.' '.$eggyolk.' '.$_SESSION[$eggyolk].' X</a>';
        echo '</TD></TR>';
        $countess++;
        }
    if($cart==''){
        echo '<TR><TD colspan=2></TD><TD align=center colspan=3><p class="txt16b" style="color: #999999"><br><br>Your Shopping Cart is Empty<br><br><br></p></TD><TD></TD></TR>';
        }
 
    if ($qtyerror==23){
        echo '<TR><TD colspan=3></TD><TD colspan=3 style="padding-left:25px"><span class="none" style="color: red; font-size: 10pt; font-weight: bold;">*invalid quantity given</span></TD></TR>';
    }
    echo '<TR><TD></TD><TD style="padding-top:5px" align=center><input type="submit" align=center STYLE="margin: 0px; padding: 0px;" value="Update Subtotal"></form></TD><TD style="padding-top:5px" align=right colspan=2><span style="color: #ffffff; font-weight: bold; ">Your Subtotal:</span></TD><TD style="padding-top:5px" align=center><span style="color: #ffffff; font-weight: bold; ">$';
    echo $_SESSION[total];
    echo '</span></TD><TD></TD></TR>';
    echo '</Table>';
}

Re: Please help me fix this puzzling shopping cart problem

Posted: Fri Aug 08, 2008 8:00 pm
by Stryks
<br> wrote:This code is a lot nicer... I usually just code in non-indented lines using notepad, but it's nice to be able to follow the brackets without counting...
Indenting is a real lifesaver, especially when you get into code like this. To make it easier, why dont you take a look at some of the other free notebook variants out there. I hear notepad++ is pretty good.

There is a running commentary on the best tools out there HERE.
<br> wrote:As far as security goes, the most valuable thing we're going to store here is customer emails in a MySQL database... going to implement paypal website payments standard with cart upload (so people don't go to paypal's site until they hit proceed to checkout) so I won't have anything worth stealing data-wise. Keeping that in mind, what security should I implement?
Securing your users information has to be one of the core drivers for site security, but in this case, you'd probably be *lucky* if information was all they were after. As it stands, a malicious user could alter peoples accounts, delete users or products, insert offensive data to be displayed to users, or just plain delete all of your data entirely. Yes, it's that bad.

Have a search on these forums for 'sql injection' to get an idea of the problem and some solid solutions.

As for reworking your code ... seriously, I'd consider rewriting the entire storage mechanism to something along the lines of what I showed above. As I said, if you want to go down that road, I'm happy to help you out getting it going, but as it stands .... it's all a bit too convoluted and time consuming for me to sink my teeth into. If it were my code I was revising, I'd scrap it and use a cleaner method.

Probably not what you want to hear, but ...

Re: Please help me fix this puzzling shopping cart problem

Posted: Sat Aug 09, 2008 1:35 pm
by <br>
As far as the sizing goes, I fixed it. I was storing the item's sizing in the session along with the current $cart_counter... the problem was that a given item's spot in the cart_count could change when items were added or deleted. I stored the sizing tagged with the $id of the item so it is now associated with the item id and not the $cart_counter's position.

My method for storing in the session functions basically like an array when it comes down to it. All unique cart ids are looped and all the information for a given item is stored in $_SESSION[anyattribute.$cart_counter].

The display portion of the shopping cart then receives the number of unique items via $_SESSION and loops that many times displaying the $_SESSION[anyattribute.$cart_counter] variables for each row.

This is where sizing is added:

Code: Select all

if ($row[id]==$_GET['id'] && isset($itemsize)){
if (empty($_SESSION[rowopt.$row[id]]) || $_SESSION[rowopt.$row[id]]==''){
$option_empt='empty';
} else {
$option_empt='';
}
if ($option_empt != 'empty'){
$_SESSION[rowopt.$row[id]]=$_SESSION[rowopt.$row[id]].', '.$itemsize;
} else if ($option_empt == 'empty') {
$_SESSION[rowopt.$row[id]]=$itemsize;
}
}
$itemsize is set during action=add_item on so the code executes if something is added and the id of that added item is the id currently being looped. Upon removal of that item, $_SESSION[rowopt.$_GET[id]] is wiped clean. Now I need to allow qty changes of items that have multiple sizes, presumably by displaying the sizes in different rows for the user so there are separate qty inputs and remove from cart buttons for different sizes... $_SESSION[rowopt.$_GET[id]] will be exploded and rebuilt based on the different quantities... it's stored as 'M,S,4X,S,L'.

Re: Please help me fix this puzzling shopping cart problem

Posted: Sat Aug 09, 2008 8:14 pm
by Stryks
I get what you are saying, and it's clear what you are doing, but my question really is why?

It has numerous drawbacks, the primary one being that you need to explode, modify and then implode your delimited strings from the session on every use. Admittedly, the size of the array and the actions performed are pretty inexpensive, performance-wise, it's still a bit of a waste of time.

Branching the cart data into a multidimensional array gives you instant access to the data, requires much less processing, and means that all cart data is stored under a single 'cart' key. I don't know how familiar you are with arrays, but they really can be quite simple once you get your head around it.

I mean, for example ... there is a bit of work removing an item from your method. You have to explode and traverse several strings, remove the item in question and then reassemble all of the strings and update them. With the method I proposed, you pass a single unset() and the job is done.

Change quantity, your process is similar to the above, mine is a simple cart-item-quantity = $new_quantity.

Writing back to the database is a snap .... just iterate through the array and write the data.

With your options though, I'd probably add them to a new database table and use the key as the value in your options dropdown instead of a text representation. Then have another new table showing the relationship of options to products. Possibly not so important now, but later on you might have items that aren't available in all sizes, or have different options. Managing all of that through the database will allow you to use the same cart mechanism to store any kind of option (size, color, style, whatever).

Anyhow, if you're happy with what you have and it's working ... great. Just throwing out some ideas for you.

Cheers :)

Re: Please help me fix this puzzling shopping cart problem

Posted: Sat Aug 09, 2008 8:48 pm
by <br>
I based this cart off of am example shopping cart that is posted online, which is where I got the basic outline from... including retrieving all the POST variable at the beginning of the scripts (but not the hilariously witty variable names). Each item in my database does have sizes stored with it, delineated by commas in the same way. You choose sizes for a given item with checkboxes and can edit the choices later if a size becomes unavailable or whatever.

As for security, I'm going to work on that... I need to eliminate all potential for ' and " in strings that I use for queries, right? Run mysql_real_escape_string() on, say, '$id' before it enters a select statement?

Back to the code: http://www.thenextlevelunlimited.com/

I've almost got this one worked out... I'm going to have a go at your method, but I've come to far to go back on this project, and my code is nearly completed. I'm using increment arrows for quantity changes now and it works almost completely (need to tinker a bit tomorrow). Here's the new code for anyone who might care:

Code: Select all

<?php
session_start();
$cart = $_SESSION['cart'];
 
if ($_GET['action'] == 'add_item'){
    $itemsize=$_POST['options'];
    $cart = $_SESSION['cart'];
        if ($cart!='' && $cart!=' ') {
        $cart .= ','.$_GET['id'];
        } else {
        $cart = $_GET['id'];
        }
    $_SESSION['cart'] = $cart;
}
 
if ($_GET['action']=='up'){
    $cart = $_SESSION['cart'];
    $cart=$cart.','.$_GET[id];
    $_SESSION['cart']=$cart;
 
    $opt_sesh=$_SESSION[rowopt.$_SESSION[$_GET[id]]];
    $opt_sesh=$opt_sesh.','.$_GET[size];
    $_SESSION[rowopt.$_SESSION[$_GET[id]]]=$opt_sesh;
}
 
if ($_GET['action']=='down'){
    $cart = $_SESSION['cart'];
 
    if ($cart==$_GET[id]){
        $cart='';
        $_SESSION['cart'] = $cart;
    }
    if ($cart) {
        $items = explode(',',$cart);
        $newcart = '';
        foreach ($items as $item) {
            if ($_GET[id] != $item || $i==1) {
                if ($newcart != '') {
                $newcart .= ','.$item;
                } else {
                $newcart = $item;
                }
            } else {
            $i=1;
            }
        }
        $cart = $newcart;
    }
 
    $_SESSION['cart']=$cart;
 
    $opt_sesh=$_SESSION[rowopt.$_SESSION[$_GET[id]]];
 
    if ($opt_sesh==$_GET[size]){
        $opt_sesh='';
        $_SESSION[rowopt.$_SESSION[$_GET[id]]] = $opt_sesh;
    }
    if ($opt_sesh) {
        $the_sizes = explode(',',$opt_sesh);
        $new_opt_sesh = '';
        foreach ($the_sizes as $the_size) {
            if ($_GET[size] != $the_size || $i==1) {
                if ($new_opt_sesh != '') {
                $new_opt_sesh .= ','.$the_size;
                } else {
                $new_opt_sesh = $the_size;
                }
            } else {
            $i=1;
            }
        }
        $opt_sesh = $new_opt_sesh;
    }
 
    $_SESSION[rowopt.$_SESSION[$_GET[id]]]=$opt_sesh;
}
 
 
if ($_GET['action']=='delete'){
    $id=$_GET['id'];
    $_SESSION['rowopt'.$id]='';
 
        if ($cart==$id){
            $cart='';
            $_SESSION['cart'] = $cart;
        }
 
        if ($cart) {
        $items = explode(',',$cart);
        $newcart = '';
            foreach ($items as $item) {
 
                if ($id != $item) {
                    if ($newcart != '') {
                    $newcart .= ','.$item;
                    } else {
                    $newcart = $item;
                    }
                }
            }
        $cart = $newcart;
    }
 
}
 
 
 
$_SESSION['cart'] = $cart;
$column==1;
 
 
$items = explode(',',$cart,100);
$cart = implode(',',$items);
$_SESSION[num_items] =count($items);
$inlist = implode(", ",$items);
$contents = array();
 
foreach ($items as $item) {
    $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
    }
 
$_SESSION[unique_items] =count($contents);
ksort($contents);
 
if($_SESSION[cart] != ''){
    $con = mysql_connect('XXX', 'XXX', 'XXX') or die(mysql_error());
    mysql_select_db('XXX') or die(mysql_error());
    $query  = "SELECT * FROM items WHERE id IN ($inlist)";
    $result = mysql_query($query) or die(mysql_error());
    $cart_counter=1;
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        if ($row[id]==$_GET['id'] && isset($itemsize)){
                if (empty($_SESSION[rowopt.$row[id]]) || $_SESSION[rowopt.$row[id]]==''){
                $option_empt='empty';
                } else {
                $option_empt='';
                }
                if ($option_empt != 'empty'){
                $_SESSION[rowopt.$row[id]]=$_SESSION[rowopt.$row[id]].','.$itemsize;
                } else if ($option_empt == 'empty') {
                $_SESSION[rowopt.$row[id]]=$itemsize;
                }
            }   
            
        if($_SESSION[rowopt.$row[id]]!='' || !isset($_SESSION[rowopt.$row[id]])){
        $size = explode(',',$_SESSION[rowopt.$row[id]]);
        $unique_sizes=array_count_values($size);
        $_SESSION[num_of_sizes.$row[id]]=count($unique_sizes);
        $sizing_counter=1;
        foreach ($unique_sizes as $size_val=>$occurences){
        $_SESSION[size.$row[id].$sizing_counter]=$size_val.'.'.$occurences;
        $sizing_counter++;
        }
        }
        
        $cart_counter++;
    }
 
    $con = mysql_connect('XXX', 'XXX', 'XXX') or die(mysql_error());
    mysql_select_db('XXX') or die(mysql_error());
    $query  = "SELECT * FROM items WHERE id IN ($inlist)";
    $result = mysql_query($query) or die(mysql_error());
    $cart_counter=1;
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $_SESSION[rowMT.$cart_counter]=$row[image75];
        $_SESSION[rowid.$cart_counter]=$row[id];
        $_SESSION[rowlnk.$cart_counter]= $row[cat1].'?id='.$row[id];
        $_SESSION[rowname.$cart_counter]=$row[name];
        $_SESSION[rowquant.$cart_counter]=$contents[$row[id]];
        $_SESSION[rowprice.$cart_counter]=$row['price'];
        $_SESSION[rowsum.$cart_counter] =($_SESSION[rowprice.$cart_counter]*$_SESSION[rowquant.$cart_counter]);
        $cart_counter++;
        }
    $cart_counterB=1;
    $additives = array();
    while ( $cart_counterB <= $_SESSION[unique_items] ){
        $additives[$cart_counterB] = $_SESSION[rowsum.$cart_counterB];
        $cart_counterB++;
        $_SESSION[total]=array_sum($additives);
        }
    }else{
    $_SESSION[total]=0;
    $_SESSION[num_items]=0;
    }
    if($_SESSION['cart']==''){
    $_SESSION[unique_items]=0;
    }
$_SESSION['cart'] = $cart;
if ($_GET['action']=='delete' || $_GET['action']=='update' || $_GET['action']=='sizerem' || $_GET['action']=='down' || $_GET['action']=='up'){
    header("location:http://www.TheNextLevelUnlimited.com/shoppingcart");
    } else {
    $backbackback='http://www.TheNextLevelUnlimited.com'.$_SESSION[goback];
    if(isset($_SESSION[gobackid])){
        $backbackback='http://www.TheNextLevelUnlimited.com'.$_SESSION[goback].'?id='.$_SESSION[gobackid];
        }
    header("location: $backbackback");
    }
 
?>
The external cart... now different sizes of same items are displayed in seperate columns with quantity changing almost working:

Code: Select all

if ($exploded_url[1] == 'shoppingcart') {
 
function convertnums($num){
$num=str_replace('0','<image src="/image/0.gif">',$num);
$num=str_replace('1','<image src="/image/1.gif">',$num);
$num=str_replace('2','<image src="/image/2.gif">',$num);
$num=str_replace('3','<image src="/image/3.gif">',$num);
$num=str_replace('4','<image src="/image/4.gif">',$num);
$num=str_replace('5','<image src="/image/5.gif">',$num);
$num=str_replace('6','<image src="/image/6.gif">',$num);
$num=str_replace('7','<image src="/image/7.gif">',$num);
$num=str_replace('8','<image src="/image/8.gif">',$num);
$num=str_replace('9','<image src="/image/9.gif">',$num);
echo $num;
}
 
    $qtyerror=$_GET[qtyerror];
    $_SESSION[goback]=$backbuttonurl;
    $_SESSION[gobackid]=$backbuttonid;
 
    echo '<Table width=655 cellspacing=0 cellspadding=0><TR><TD style="padding-bottom: 10px" align=left nowrap><p class="mainheader">Your Shopping Cart</p></TD><TD style="padding-left: 35px;padding-bottom: 10px" width="100%"><a style="font-size: 9pt; color: rgb(153, 153, 153);" href="';
    $backbackback='http://www.TheNextLevelUnlimited.com'.$_SESSION[goback];
    if(isset($_SESSION[gobackid])){
        $backbackback='http://www.TheNextLevelUnlimited.com'.$_SESSION[goback].'?id='.$_SESSION[gobackid];
    }
    echo $backbackback.'">< <strong>back to shopping</strong></a></TD></TR></Table>';
    if($cart==''){
        $_SESSION[unique_items]=0;
    }
    echo '<Table width=655 cellspacing=0 cellspadding=0><TR><TD align=center width=75> </TD><TD width=160 align=center><u><span style="color: #ffffff; font-weight: bold; text-decoration: underline">Item</span></u></TD><TD align=center><u><span style="color: #ffffff; font-weight: bold; text-decoration: underline">Price</span></u></TD><TD width=100 align=center><u><span style="color: #ffffff; font-weight: bold; text-decoration: underline;">Quantity</span></u></TD><TD width=130 align=center><u><span style="color: #ffffff; font-weight: bold; text-decoration: underline">Total</span></u></TD></TR>';
    $countess=1;
    while ( $countess <= $_SESSION[unique_items] ){
        if ($_SESSION[num_of_sizes.$_SESSION[rowid.$countess]] > 1){
            $i=1;
            while($i<=$_SESSION[num_of_sizes.$_SESSION[rowid.$countess]]){
                $size_and_occ=$_SESSION[size.$_SESSION[rowid.$countess].$i];
                $size_occ_array=explode('.',$size_and_occ,2);
                $thatsize=$size_occ_array[0];
                $thatquant=$size_occ_array[1];
                $thatsubtot=($thatquant*$_SESSION[rowprice.$countess]);
                echo '<TR><TD align=left style="padding-bottom: 10px; "><a href="';
                echo $_SESSION[rowlnk.$countess];
                echo '" target="_BLANK"><image src="/image/';
                echo $_SESSION[rowMT.$countess];
                echo '" border=0></a></TD><TD class="txt14b" align=left style="padding-left:15px"><span style="color: #ffffff; font-weight: bold; ">';
                echo $_SESSION[rowname.$countess];
                echo ' ('.$thatsize.')</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; "><image src="/image/DSign.gif">';
                convertnums($_SESSION[rowprice.$countess]);
                echo '</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; ">';
                convertnums($thatquant);
                echo '<image src="/spacer.gif" width=4 height=1><a href="cart.php?action=up&id=';
                echo $_SESSION[rowid.$countess];
                echo '&size='.$thatsize.'"><image src="/image/plus.gif" border=0></a><a href="cart.php?action=down&id=';
                echo $_SESSION[rowid.$countess];
                echo '&size='.$thatsize.'"><image src="/image/minus.gif" border=0></a>';
                echo '</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; "><image src="/image/DSign.gif">';
                convertnums($thatsubtot);
                echo '</span></TD></TR>';
                $i++;
            }
        } else {
        echo '<TR><TD align=left style="padding-bottom: 10px; "><a href="';
        echo $_SESSION[rowlnk.$countess];
        echo '" target="_BLANK"><image src="/image/';
        echo $_SESSION[rowMT.$countess];
        echo '" border=0></a></TD><TD class="txt14b" align=left style="padding-left:15px"><span style="color: #ffffff; font-weight: bold; ">';
        echo $_SESSION[rowname.$countess];
        echo ' (';
        if (strrpos($_SESSION[rowopt.$_SESSION[rowid.$countess]],',')=='FALSE'){
        echo $_SESSION[rowopt.$_SESSION[rowid.$countess]];
        } else {
        $display_size=explode(',',$_SESSION[rowopt.$_SESSION[rowid.$countess]]);
        echo $display_size[0];
        }
        echo ')</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; "><image src="/image/DSign.gif">';
        convertnums($_SESSION[rowprice.$countess]);
        echo '</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; ">';
        convertnums($_SESSION[rowquant.$countess]);
        echo '<image src="/spacer.gif" width=4 height=1><a href="cart.php?action=up&id=';
        echo $_SESSION[rowid.$countess];
        echo '&size=';
        if (strrpos($_SESSION[rowopt.$_SESSION[rowid.$countess]],',')=='FALSE'){
        echo $_SESSION[rowopt.$_SESSION[rowid.$countess]];
        } else {
        $display_size=explode(',',$_SESSION[rowopt.$_SESSION[rowid.$countess]]);
        echo $display_size[0];
        }
        echo '"><image src="/image/plus.gif" border=0></a><a href="cart.php?action=down&id=';
        echo $_SESSION[rowid.$countess];
        echo '&size=';
        if (strrpos($_SESSION[rowopt.$_SESSION[rowid.$countess]],',')=='FALSE'){
        echo $_SESSION[rowopt.$_SESSION[rowid.$countess]];
        } else {
        $display_size=explode(',',$_SESSION[rowopt.$_SESSION[rowid.$countess]]);
        echo $display_size[0];
        }
        echo '"><image src="/image/minus.gif" border=0></a>';
        echo '</span></TD><TD class="txt14b" align=center><span style="color: #ffffff; font-weight: bold; "><image src="/image/DSign.gif">';
        convertnums($_SESSION[rowsum.$countess]);
        echo '</span></TD></TR>';
        }
        $countess++;
        }
    if($cart==''){
        echo '<TR><TD colspan=2></TD><TD align=center colspan=3><p class="txt16b" style="color: #999999"><br><br>Your Shopping Cart is Empty<br><br><br></p></TD><TD></TD></TR>';
        }
 
    if ($qtyerror==23){
        echo '<TR><TD colspan=3></TD><TD colspan=3 style="padding-left:25px"><span class="none" style="color: red; font-size: 10pt; font-weight: bold;">*invalid quantity given</span></TD></TR>';
    }
    echo '<TR><TD></TD><TD style="padding-top:5px" align=center></TD><TD style="padding-top:5px" align=right colspan=2><span style="color: #ffffff; font-weight: bold; ">Your Subtotal:</span></TD><TD style="padding-top:5px" align=center><span style="color: #ffffff; font-weight: bold; "><image src="/image/DSign.gif">';
    convertnums($_SESSION[total]);
    echo '</span></TD><TD></TD></TR>';
    echo '</Table>';
}

Re: Please help me fix this puzzling shopping cart problem

Posted: Sat Aug 09, 2008 10:47 pm
by Stryks
Well ... I don't know about you, but for me, projects are never completed, they just enter the next revision. Oh, they're complete, and online, but as you find better methods and overcome old issues, you go back and revise. Especially when you start to realize security vulnerabilities in your old methods.

But yeah, I had a little time so I've tacked together a more complete version of the alternate sessions method I've been advocating for you.

It is untested (I'm off site on a friends computer), but I think the core of it should work without too many problems.

Code: Select all

<?php
    session_start();
 
    // VALIDATE THINGS THAT WILL BE STORED(database / sessions) OR DISPLAYED
    if(isset($_GET['id'])) {
        if(!is_numeric($_GET['id'])) {
            echo 'Validation failed - trigger error handling method';
            exit();
        }
    }
    if(isset($_POST['options'])) {
        if(!ctype_alnum($_POST['options'])){
        echo 'Validation failed - trigger error handling method';
        exit();        
        }
    }
    if(isset($_POST['qty'])) {
        if(!ctype_alnum($_POST['qty'])){
        echo 'Validation failed - trigger error handling method';
        exit();        
        }
    }
 
//  ACTION ADD    
    if ($_GET['action'] == 'add'){
        // If the ID added is present in the cart and it is of the same size ...
        if(isset($_SESSION['cart'])) {
            foreach($_SESSION['cart'] as $cart_id=>$cart_item) {
                if(($cart_item['id'] == $_POST['item_id']) && ($cart_item['id'] == $_POST['option'])) {
                    // ... increase the current item qty by 1
                    $_SESSION['cart'][$cart_id]['qty'] += 1;
                    break;
                }
            }
        } else {
            // Connect to the database and fetch product information
            $con = mysql_connect('XXXX.db', 'XXXX', 'XXXX') or die(mysql_error());
            mysql_select_db('items') or die(mysql_error());
 
            $query  = "SELECT item_name, item_cost FROM items WHERE id='" . mysql_real_escape_string($_POST['item_id']) . "'";
            $result = mysql_query($query) or die(mysql_error());
            $DB_DATA = mysql_fetch_assoc($result);
 
            // ... otherwise we need to add this new item to the cart
            $_SESSION['cart'][] = array('id'=>$_GET['id'], 'desc'=>$DB_DATA['item_name'], 'option' => $_POST['option'], 'cost'=>$DB_DATA['item_cost'], 'qty'=>1);
        }
    }
//  ACTION REMOVE
    if ($_GET['action'] == 'remove') {
        if(isset($_SESSION['cart'][$_GET['id']])) unset($_SESSION['cart'][$_GET['id']]);    
    }
//  ACTION MODIFY   (currently ony configured for qty modifications)
    if ($_GET['action'] == 'modify') {
        if (isset($_POST['qty']))) {
            if(isset($_SESSION['cart'][$_GET['id']])) {
                $_SESSION['cart'][$_GET['id'] = $_POST['qty'];    
            }            
        }
    }
?>
 
This assumes that the new item is being added by POST request, but you could just as easily do it with GET.

The 'modify' action is for specifically setting the quantity, but an increment function would be as easy as.

Also, by packing the cart with values from the database when added, you can draw the cart completely from the $_SESSION array.

Code: Select all

<table border="0" cellpadding="0" cellspacing="0">
   <tr>
      <th>Qty</th>
      <th>Item Description</th>
      <th>Unit Cost</th>
      <th>Order Cost</th>
      <th>Tools</th>
   </tr>
<?php
    foreach($_SESSION['cart'] as $cart_id=>$cart_item) {
?>
   <tr>
      <td><?php echo $cart_item['qty']; ?></td>
      <td><?php echo $cart_item['desc'] . " (" . $cart_item['option'] . ")"; ?></td>
      <td>$<?php echo number_format($cart_item['cost'], 2, ".", ","); ?></td>
      <td>$<?php echo number_format($cart_item['cost'] * $cart_item['qty'], 2, ".", ","); ?></td>
      <td><a href="process_page.php?action=remove&id=<?php echo $cart_id; ?>">[ remove ]</a></td>
   </tr>
<?php
    }
    $cart_cost = 0;
    if(isset($_SESSION['cart'])) {
        foreach($_SESSION['cart'] as $item_data) $cart_cost += $item_data['cost']; 
    }
    $cart_cost = number_format($cart_cost, 2, ".", ",");
?>
   <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>$<?php echo $cart_cost; ?></td>
      <td>&nbsp;</td>
   </tr>
 
</table>
 
That's very basic obviously, but you get the drift.

As for pulling basic stats about the cart ... it's as easy as ...

Code: Select all

<?php
    $cart_count = 0;
    $cart_cost = 0;
    if(isset($_SESSION['cart'])) {
        foreach($_SESSION['cart'] as $item_data) {
            $cart_count++;
            $cart_cost += $item_data['cost']; 
        }
    }
    $cart_cost = number_format($cart_cost, 2, ".", ",");
 
    echo "There are " . count($_SESSION['cart']) . " unique items in the cart ($cart_count total) with a total cost of $" . $cart_cost;    
?>
 
I hope this comes in handy for you at some point.

Cheers. :)

Re: Please help me fix this puzzling shopping cart problem

Posted: Sun Aug 10, 2008 1:02 pm
by <br>
Thanks for all of your help, Stryks. Also, thanks for the sample code, I'm going to come back to it as soon as I'm done with this in a day or two and I'm sure many others will find it helpful as well.

Jacob