Hi all,

I am trying to implement a vary simple shopping cart for my website. I have been looking around the web and haven't quite found the answers I am looking for.

I have decided to use sessions, and basically set up some arrays, and then, here is the confusion:

How do I grab the information about each product displayed in my catalog and input them into the array I set up, which can then be used to fill the cart later on. I am using an ODBC connection to query my stock.

I have thousands of products, which means I cannot manually code each item as its own array. I have looped my query information so that, using php, the desc, price and a 'add to cart' button is automatically displayed for each product. So I am now confused as to how to identify each product when their individual 'add to cart' button is clicked, and then get the desc and price details into that array.

Any help regarding this matter is much appreciated, thanks.

    i assume each product is stored in the database with a unique number (primary key field). use those numbers on you web forms when allowing users to choose which product(s) they want. when the users add product(s) to their cart, query the db and grab all of the info on that product and store it in the session.

      Thanks, but how do I store the information in a session, arrays?

      Pleas could you provide me with an example of the code I would use to do this. Much appreciated, thanks again.

        here is a very very basic example (no error checking, etc...). let's say you have a "products" table that has 3 fields: product_id, description, price. and you are showing product numbers 1-3:

        session_start();
        
        // assume already connected to db
        
        $result = mysql_query('SELECT * FROM products WHERE product_id IN(1,2,3)');
        while ($row = mysql_fetch_assoc($result)) {$products[$row['product_id']] = $row;}
        
        if (!isset($_POST['submit']))
        {
        	echo '
        	Product list:
        	<form action="' . $_SERVER['PHP_SELF'] . '" method="POST">
        	';
        
        foreach ($products as $key => $value)
        {
        	extract($value);				
        	echo '	
        	product #: ' . $product_id . '<br>
        	description: ' . $description . '<br>
        	price: $' . $price . '<br>
        	quantity: <input type="text" name="' . $key . '[quantity]" size="2"><br>
        	<input type="submit" name="' . $key . '[submit]" value="add to cart">
        	<br>
        	<br>
        	';
        }
        echo '
        <input type="hidden" name="submit" value="add to cart">
        </form>
        ';
        }
        
        if (isset($_POST['submit']))
        {
        	foreach ($_POST as $key => $value)
        	{
        		if (isset($value['submit']))
        		{
        			$_SESSION['cart'][$key] = $products[$key];
        			$_SESSION['cart'][$key]['quantity'] = $value['quantity'];
        			break;
        		}		
        	}
        
        echo 'your cart:<br><br>';
        $total = 0;
        
        foreach ($_SESSION['cart'] as $key => $value)
        {
        	extract($value);
        	echo '
        	product #: ' . $product_id . '<br>
        	description: ' . $description . '<br>
        	price: $' . $price . '<br>
        	quantity: ' . $quantity . '<br><br>';
        	$total =+ $quantity * $price;
        }
        echo 'total: $' . $total;
        }
        

          Totally appreciate your effort in coding all that. I will try it out asap.

          I have however just noticed a couple of possible issues I may have. One is the fact that in your example you are grabbing only specific product_id's i.e. IN (1,2,3); And in my database there are over 20000 products with individual id's of their own barcodes. As you can imagine, I don't really want to be typing all them out. I have managed to however, successfully display my items in the database through another SQL query and it works fine, am I ok to just stick with that?

          Another thing is potentially aquiring that information stored in the session again when accessing the cart itself. I tryed before hand to use the following:

          $name = $POST['name'];
          $
          SESSION['name'] = $name;
          echo $_SESSION['name'];

          And grabbed the information 'name' from hidden fields, (which in turn were getting their values from the database fields) on my products page. Would this still be the correct method or can you sugest another?

          Thanks, yet again.

            Originally posted by chrislead
            Totally appreciate your effort in coding all that. I will try it out asap.

            I have however just noticed a couple of possible issues I may have. One is the fact that in your example you are grabbing only specific product_id's i.e. IN (1,2,3); And in my database there are over 20000 products with individual id's of their own barcodes. As you can imagine, I don't really want to be typing all them out. I have managed to however, successfully display my items in the database through another SQL query and it works fine, am I ok to just stick with that?

            This is what the sku/product ID is for. Surely the code knows what products are being shown? You don't have all 20,000 products on the same page, I trust 😉

            In the cart I'm trying to finish this week, we use a text link that says "Add this item to my cart" that refers to "show_cart.php?action=add&sku=$sku", so the cart script knows that we are adding an "$sku" to our cart. After the "$sku" is added the cart is displayed with select boxes in case they wish to change color, quantity, etc....

              I can understand that, i think.

              Here is my code for displaying the items in my database (it may give you an idea of where I am now in relation to what I am aiming for):

              ?>
              include 'odbc.php';

              $query = odbc_exec($odbc, "SELECT DISTINCT Plus.Code, Plus.Desc, Plus.Price, Groups.GroupDesc FROM Plus, Groups WHERE Plus.Group=Groups.GroupCode AND Groups.GroupDesc='GLOSS'") or die (odbc_errormsg());
              while($row = odbc_fetch_array($query)){
              for($i=0; $i<count($row); $i++) {
              ?>
              <table width="100%" border="0" cellpadding="0">
              <tr>
              <td height="29" colspan="2"><? echo "<B>Description:</B> "?>&nbsp;<font color="#336633"><? echo $row['Desc'];?></font></td>
              <td width="23%" rowspan="3">&nbsp;</td>
              </tr>
              <tr>
              <td height="47" colspan="2" valign="top"><? echo "<B>Type:</B> ".$row['GroupDesc'];?>&nbsp;</td>
              </tr>
              <tr>
              <td width="22%" height="40"> <? echo "<B>Price:</B> "?> <font size="4" face="Eras Demi ITC" font color="FF0000">
              £<? echo number_format ($row['Price'], 2, ".", ",");?></font>
              <div align="center"></div>
              <div align="center"></div>
              <div align="center">&nbsp; </div></td>
              <td width="55%">
              <?
              $information = array('quantity' => ' ', 'description' => ' ', 'price' => ' ');
              $_SESSION ['information'] = $information;
              ?>
              <form name="form1" method="post" action="cart.php">
              Quantity:
              <input type="text" name="quantity" value="0" size="4">
              <input type="submit" name="add_to_cart" value="Add to Basket">
              <input type="hidden" name="plu" value="<? echo $row['Code']; ?>">
              <input type="hidden" name="description" value="<? echo $row['Desc']; ?>">
              <input type="hidden" name="price" value="<? echo number_format ($row['Price'], 2, ".", ","); ?>">
              </form></td>
              </tr>
              </table>
              <HR>
              <?
              }
              }
              ?>

              //Cart page:

              <?
              $quantity = $POST['quantity'];
              $plu = $
              POST['plu'];
              $description = $POST['description'];
              $price = $
              POST['price'];

              $_SESSION['quantity'] = $quantity; 
              $_SESSION['plu'] = $plu; 
              $_SESSION['description'] = $description; 
              $_SESSION['price'] = $price; 
              
              	$sub_total = $_SESSION['price']*$_SESSION['quantity'];
              	$sub_total = number_format ($sub_total, 2, ".", ",");
              
              $_SESSION['information']['quantity'] = $_SESSION['quantity'];
              $_SESSION['information']['description'] = $_SESSION['description'];
              $_SESSION['information']['price'] = $_SESSION['price'];	

              ?>
              <p>The contents of your cart:</p>
              <table width="100%" border="1" cellspacing="0" cellpadding="0">
              <tr>
              <td width="163"><div align="center"><strong>Edit</strong></div></td>
              <td width="58"><div align="center"><strong>Quantity</strong></div></td>
              <td width="469"><div align="center"><strong>Product Description</strong></div></td>
              <td width="125"><div align="center"><strong>Price</strong></div></td>
              <td width="159"> <div align="center"><strong>Sub Total</strong></div></td>
              </tr>
              <tr>
              <td valign="top"><div align="center">Delete Item</div></td>
              <td valign="top"><form name="form1" method="post" action="">
              <div align="center">
              <input name="quantity" type="text" value="<? echo $SESSION['information']['quantity'];?>" size="1" maxlength="2">
              </div>
              </form></td>
              <td height="5" align="center" valign="top" nowrap><? echo $
              SESSION['information']['description'];?></td>
              <td align="center" valign="top">&pound;<? echo $_SESSION['information']['price'];?></td>
              <td width="159" align="center" valign="top">&pound;<? echo $sub_total;?></td>
              </tr>
              </table>
              <table width="133" border="0" align="right" cellpadding="0" cellspacing="0">
              <tr>
              <td width="43"><strong>Total:</strong></td>
              <td width="90">&nbsp;</td>
              </tr>
              </table>
              <div align="right"></div>
              <p>Continue Shopping | Buy these items</p>
              <?
              //like so

              Obviously, the value I add to this cart dont stay. Tut. Can you please advise me from where to go from here, what to alter etc. Thanks.

              Basically, bottom line. I can get the items in the cart, but how do I get them to stay there in the array I have made, and then when the user adds another item, an extra row is automatically created in the cart. I am presuming I need to assign a script to the text link 'continue shopping'. which possibly saves the item in the array/session, or even a foreach loop? Thanks again.

                Basically, I think that what's needed (after a brief glimpse at your code) is a count/counter of items in the cart.

                The _SESSION array can hold arrays as well as single variables, as you probably know very well.

                So, in my cart, the first item placed in is $SESSION['cart'][0]['plu'], its color is $SESSION['cart'][0]['color'], etc.

                Then, for each subsequent addition to the cart, we first check if $SESSION['cart'][0] is set, and if it is, we add the new item to $SESSION['cart'][$ct]['plu'] , where $ct = count($_SESSION['cart']).....

                  Ok, Good sugestion, however I have already managed to add things to the cart successfully.

                  My main problem now is keeping them there. I am considering using a loop, and many examples I have seen use a foreach() loop. I.e. foreach('information' as $field=>$value) That is all well and good, but...

                  My array: $information = array('quantity' => ' ', 'description' => ' ', 'price' => ' ');

                  ...and then adding each item to the ' ' in each case. It works! however, (I may be wrong), but is there only room for one value in there? should I use "array('quantity'=>array(' ') 'description'=>array())etc" instead; would that work to hold more than one value?

                  And back to the loop:

                  So how do I loop through that array putting each value into a table...using this?:

                  foreach($information as $field=>$value){
                  echo $field;
                  echo $value;

                  ...but then making a new row in my table for each new item added. HELP!

                  then again surely I can keep: echo $_SESSION['information']['quantity']; when showing my array values and just loop them?

                  thanks

                    Originally posted by chrislead
                    Ok, Good sugestion, however I have already managed to add things to the cart successfully.

                    My main problem now is keeping them there.

                    Right, which was what my suggestion addressed. However, now I know (and I guess you did all along, but hadn't yet said), that we have a fundamental design difference in our carts: I do not write to a db until the order is confirmed, and you are keeping track of orders in a database. edit: or at least I guess you are ... maybe there's the rub 😉 I've posted a few times my reasons for doing it this way.

                    Since you're already committed, so it seems, to doing it the other way, I'll try and think up a good answer 😃

                    is there room for only one value in there?

                    Yes, in the $information array, there is room for one quantity, one description, etc. Therefore, if a new item is added to the cart (or, if somehow in your setup you can add 2 or more items at once), then your data will be overwritten in memory when the new data is put into the $information array, unless it's stored somewhere.

                    So, when an item is added to the cart, you should do a db insert immediately, or else reconsider the decision and carry everything in the SESSION, using multidimensional arrays, until some later time....

                    I probably still haven't answered your ??, but I'm not as good a communicator as I wish I were ... HTH,

                      Thanks for trying though!

                      One major prob with doing that; I am not connecting to the database to do anything other than display the products. And I am not writing any information to it when an item is selected, I can't basically. (client descision) I am using sessions and an array.

                      Did I understand you right that I AM only storing one value at a time, like I said? ...Obviously I want to store loads, or as many as the customer wants anyway. So should I use this?:

                      $information = array('quantity' => array(' '), 'description' => array(' '), 'price' => array(' '));

                      ...would that allow for multiple entries?

                      If so, how do I loop through that array and display each entry as a new row in my table? Ta again.

                      If I am just confusing everyone, then now thinking about it, I could actually create another totally fresh mysql database and like you said I think; add the items to the database instead of the array and then grab the chosen products from there. Although I have heard that it is not efficient to keep db connections open. Any suggestions?

                        I would create a Cart class, that stores an array of Product ID's and Quantity.

                        Everytime a customer buys a product it gets added to the array in the Cart class.

                        When the customer views cart, you loop through the array to display the correct product info.

                        Nick.

                          Originally posted by chrislead
                          Thanks for trying though!

                          One major prob with doing that; I am not connecting to the database to do anything other than display the products. And I am not writing any information to it when an item is selected, I can't basically. (client descision) I am using sessions and an array.

                          Did I understand you right that I AM only storing one value at a time, like I said? ...Obviously I want to store loads, or as many as the customer wants anyway. So should I use this?:

                          $information = array('quantity' => array(' '), 'description' => array(' '), 'price' => array(' '));

                          ...would that allow for multiple entries?

                          If so, how do I loop through that array and display each entry as a new row in my table? Ta again.

                          If I am just confusing everyone, then now thinking about it, I could actually create another totally fresh mysql database and like you said I think; add the items to the database instead of the array and then grab the chosen products from there. Although I have heard that it is not efficient to keep db connections open. Any suggestions?

                          I made my suggestions earlier, and I think that maybe I understood myself much better than you did ... not that I'd consider that surprising, it's very logical 😉 Sorry it hasn't been more clear. One more try:

                          You want to make the session (variable) that represents the cart a multi-dimensional array (what Perl coders call a "hash"). It doesn't matter exactly how you code it, as long as it works, and I showed you above how I implemented that.

                          In my carts: $_SESSION['cart'] is an array that contains a bunch of other arrays, each one of which contains all the necessary details about that particular item. This necessitates nested looping, a la:

                          //display cart
                          
                          //this is off the top of my head, but it's close
                          
                          foreach ($_SESSION['cart'] as $crt) {
                             foreach ($crt) {
                                echo "Item: ".$crt['plu']."<br>";
                                echo "Quan: ".$crt['quantity']."<br>";
                            // and so on...
                             }
                          }

                          It is something of a PITA to get everything right, but it works, and is very gratifying to pull off...

                          I need to spend time today AAMOF finishing up one I've been doing off/on for two years. If I finish, and could afford it, I'd take a very loooooong vacation afterwards ...

                          Good luck!

                            Appreciate your reply. I dont think I have yet got my head around the idea of storing multiple information in arrays. Totally my fault. I have about decided now that I am going to try the database approach, whereby every item added to the cart is added to a separate mysql database and then grabbed from there when needed and deleted when finished.

                            I was wondering if this would be possible: Inputting the session ID into the database along with the item added, and then when grabbing the information to display in the cart, run a query such as SELECT * FROM table where sessionid = session_id(). Would that bring out all the records which have the same session id stored as the one that has being set?

                            I have tried this and the code is having problems executing the SQL statements, error mesage "unexpected T_VARIABLE":

                            $session_id = $_COOKIE[PHPSESSID];
                            
                            "INSERT INTO cart VALUES ('"$session_id"', '"$_SESSION['description']"', '"$_SESSION['quantity']"', '"$_SESSION['price']"', '"$_SESSION['type']"', '"$_SESSION['plu']"')";

                            and again here when obtaing the information added:

                            $query = "SELECT * FROM cart WHERE session_id = '"$session_id"'";
                            
                            $result = mysql_query($query);
                            while($record = mysql_fetch_row($result)){
                            	for ($i=0; $i<count($record); $i++){
                            		echo $record[$i]."<BR>";{
                            	echo <BR>;}

                            Any help on getting this to work is much appreciated. Ta again

                              Wehey!

                              Never mind, I got it to work. I forgot the concatonation operators. ie. the dots. Code:

                              VALUES ('".$session_id."', '".$_SESSION['description']."', //etc

                              However, (there is always an 'however') I believe this computer is messed up. It displays everything multiple times!

                              I added one record to the database and succesully displayed it, well, sort of. it repeats the first result 3 times! can this be something to do with my while loop? The same occured when displaying my products initially. each record/item was displayed on the page 4 times each! Any sugestions? or even another way to loop through the items would be brill!

                              Ta.

                                Okydoky.

                                Well besides that, how about this:

                                Can you please help me on calling functions through hyperlinks and form buttons.

                                I am assuming something like this:

                                <A HREF = "cart.php?action=function name>delete<a/>

                                But it doesnt call it.

                                What type of things can you put in a hyperlink like this one, related to calling functions on a diferent page.

                                Thanks

                                  Write a Reply...