TheJoey Posted September 7, 2009 Share Posted September 7, 2009 ive seen a few examples on the net but seem very complex, what would be the easiest way to start a shopping cart that stores its data in arrays insted of a database. Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/ Share on other sites More sharing options...
RichardRotterdam Posted September 7, 2009 Share Posted September 7, 2009 ive seen a few examples on the net but seem very complex, what would be the easiest way to start a shopping cart that stores its data in arrays insted of a database. A shoppingcart that uses arrays instead of a database doesn't even exist. Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914213 Share on other sites More sharing options...
dave_sticky Posted September 7, 2009 Share Posted September 7, 2009 Sessions and Arrays... Â session_start(); $_SESSION['shopping_cart'] = array(); // And then to add items... $_SESSION['shopping_cart'][] = "Item 1"; $_SESSION['shopping_cart'][] = "Item 2"; // And to echo them back out... foreach($_SESSION['shopping_cart'] as $value) { Â echo $value . "<br />"; } Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914216 Share on other sites More sharing options...
TheJoey Posted September 7, 2009 Author Share Posted September 7, 2009 if i was to use session_start(); $_SESSION['shopping_cart'] = array(); // And then to add items... $_SESSION['shopping_cart'][] = "Item 1"; $_SESSION['shopping_cart'][] = "Item 2"; // And to echo them back out... foreach($_SESSION['shopping_cart'] as $value) { Â echo $value . "<br />"; } Â would i then be able to edit add and remove from cart? or would it be restricted Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914217 Share on other sites More sharing options...
dave_sticky Posted September 7, 2009 Share Posted September 7, 2009 Well you could add to it by having a "Add To Cart Link" which could pass the item to a script in the URL... Â <a href='<?PHP echo $_SERVER['REQUEST_URI']; ?>&action=add_to_cart&item=ItemName'>Add To Cart Link</a> Â if($_GET['action'] == "add_to_cart") { Â $_SESSION['shopping_cart'][] = $_GET['item']; } Remove is a little more tricky, but you'd need a remove link next to each item in the cart... Â foreach($_SESSION['shopping_cart'] as $key => $value) { echo $value . "<a href='" . $_SERVER['REQUEST_URI'] . "&action=remove_item&itemkey=" . $key ."'>Remove</a>"; } if($_GET['action'] == "remove_item") { unset($_SESSION['shopping_cart'][$_GET['itemkey']]); } This is all just off the top of my head, I've not tested it. But it's the basics of what you need to make it work! Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914224 Share on other sites More sharing options...
TheJoey Posted September 7, 2009 Author Share Posted September 7, 2009 ill keep u posted its really late . thanks for your help. Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914226 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 When i try to use one of the href from the links i get this error ERROR 403 Access forbidden Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914449 Share on other sites More sharing options...
thewooleymammoth Posted September 8, 2009 Share Posted September 8, 2009 your gonna have to use databases or files at one point or another, another, but here is one that i wrote a while ago, you can look at if you want. it uses arrays to keep track of items in the cart, but uses a database to keep track of items available for purchase. cart page <?php defined("pc") or die("no direct access allowed"); $con=mysql_connect(host, sql_user, sql_pass);     mysql_select_db(db);   if(isset($_GET['addproductid']))   {     $id=mysql_real_escape_string($_GET['addproductid']);     if(isset($_GET['qty']))     {       $qty=mysql_real_escape_string(strip_tags(htmlspecialchars($_GET['qty'])));       $sql="SELECT * FROM `shop_products` WHERE `id` = '$id' LIMIT 1;";       $product=mysql_fetch_assoc(mysql_query($sql));       $views=$product['views'];       $purchased=$product['times_purchased'];       if($purchased < 1)       {         $purchased=1;       }       $purchased=$purchased + $qty;       $rating=$views * $purchased;       $sql="UPDATE `shop_products` SET `times_purchased` = '$purchased', `rating` = '$rating' WHERE `id` = '$id' LIMIT 1";       mysql_query($sql);     }     else     {      $qty=1;     }     if(isset($_SESSION['cart']["$id"]))     {      $old=explode(' ', $_SESSION['cart']["$id"]);      $oldqty=$old['1'];      $newqty=$oldqty + $qty;      $_SESSION['cart']["$id"]="$id $newqty";     }     else     {      $_SESSION['cart']["$id"]="$id $qty";     }   }   elseif(isset($_POST['updateqty']))   {     if(isset($_SESSION['cart']["$id"]))     {      unset($_SESSION['cart']["$id"]);     }     $id=$_POST['updateqtyid'];     $qty=$_POST['updateqty'];     $_SESSION['cart']["$id"]="$id $qty";   }   elseif(isset($_GET['remove']))   {     $id=mysql_real_escape_string($_GET['remove']);     if(isset($_SESSION['cart']["$id"]))     {      unset($_SESSION['cart']["$id"]);     }     echo "     <div id='message'>     Item removed     </div>     ";   }   echo "   <div id='cartmain'>   ";   if(is_array($_SESSION['cart']) && count($_SESSION['cart']) > 0)   {     echo"<table id='carttable' width='80%'>       <tr class='demo' valign='top'>         <td width='30%'>           <b>Quantity</b><br /><br />         </td>         <td width='40%' >           <b>Product Name</b>         </td>         <td width='10%' align='right'>           <b>Price</b>         </td>         <td width='30%' align='right'>         <b>Item Total</b>         </td>       </tr>         ";         $total=0;     foreach($_SESSION['cart'] as $product)     {       $product=explode(" ", $product);       $id=$product[0];       $qty=$product[1];       $sql="SELECT * FROM `shop_products` WHERE `id` = '$id' LIMIT 1;";       $product=mysql_fetch_array(mysql_query($sql));       $name=htmlspecialchars(stripslashes($product['name']));       $price=$product['price'];       $pricee=number_format($product['price'], 2);       $subtotal=$price * $qty;       $subtotale=number_format($subtotal, 2);       $subtotalp=str_replace(",", "", $subtotal);       $total = $total + $subtotal;       $totale=number_format($total, 2);       echo "       <tr valign='top'>         <td>           <form method='post' action='?viewcart'>           <input type='hidden' name='updateqtyid' value='$id' />           <input type='text' name='updateqty' size='2' value='$qty' />           <input type='submit' value='update' /><br />           <a href='?viewcart&remove=$id'>Remove</a><br />           </form>         </td>         <td>           <a href='?product&productid=$id'>$name</a>         </td>         <td align='right'>           $".$pricee."         </td>         <td align='right'>         $".$subtotale."         </td>       </tr>       ";     }     echo "     <tr>       <td>       </td>       <td>       </td>       <td align='right'>       <b>Sub-Total:</b>       </td>       <td align='right'>     $".$totale."       </td>     </tr>     </table>     ";     $pageurl=page_url();     $pageurl=explode("?", $pageurl);     $pageurlreturn=$pageurl[0] . "?return";     $pageurlconfirm=$pageurl[0] . "?confirm";     $_SESSION['total']=$total;     echo "<form action='https://www.paypal.com/cgi-bin/webscr' method='post'>               <input type='hidden' name='cmd' value='_xclick'>               <input type='hidden' name='upload' value='1'>               <input type='hidden' name='business' value='*youremail here'>               <input type='hidden' name='item_name' value='Miners_Cart_Checkout'>               <input type='hidden' name='amount' value='$total'>               <input type='hidden' name='quantity' value='1'>               <input type='hidden' name='notify_url' value='$pageurlconfirm'>               <INPUT TYPE='hidden' name='return' value='$pageurlreturn'>               <input type='submit' value='Checkout'>               </form>     ";   }   else   {     echo "     You have no items in your cart     ";   }   echo "<a href='?'>Continue Shopping?</a>";   echo"</div>"; mysql_close($con); ?> browse page <?php defined("pc") or die("no direct access allowed");   $con=mysql_connect(host, sql_user, sql_pass);   mysql_select_db(db);     $sql="SELECT * FROM `shop_products`";     if(isset($_GET['sort']))     {      $sort=mysql_real_escape_string($_GET['sort']);      $sql.= " ORDER BY `$sort` ASC";     }   $query=mysql_query($sql);   echo "   <table width='600px' id='browse_table' >       <tr>         <td width='80%'>         Name:         </td>         <td width='20%'>         Price         </td>       </tr>";   while($q = mysql_fetch_assoc($query))   {      $name=stripslashes($q['name']);      $id=$q['id'];      $price=number_format($q['price'], 2);      $image=$q['image'];      echo "      <tr><td><a href='?product&productid=$id'>$name</a></li></td><td>$".$price."</td></tr> <br />      ";   }   echo "   </table>   ";   mysql_close($con); ?> the page for a single item <?php defined("pc") or die("no direct access allowed");   require_once($_SERVER['DOCUMENT_ROOT'].install."/scripts/shop/functions.php");   $con=mysql_connect(host, sql_user, sql_pass);   mysql_select_db(db);   if(isset($_GET['productid']))   {     $id=mysql_real_escape_string($_GET['productid']);     $sql="SELECT * FROM `shop_products` WHERE `id` = '$id' LIMIT 1;";     $product=mysql_fetch_assoc(mysql_query($sql));     $views=$product['views'];     $views++;     $purchased=$product['times_purchased'];     if($purchased < 1)     {      $purchased=1;     }     $rating=$views * $purchased;     $sql="UPDATE `shop_products` SET `views` = '$views', `rating` = '$rating' WHERE `id` = '$id' LIMIT 1";     mysql_query($sql);     $name=htmlspecialchars(stripslashes($product['name']));     $des=stripslashes($product['description']);     $price=$product['price'];     $img=$product['image'];     echo "<h3>$name</h3>";     echo "     <div style='width:600px;'>       <table valign='top'>       <tr>       <td>         <img src='$img' width='250' />       </td>       <td valign='top'>";       echo "$".$price;       add_to_cart($id);       echo "       </td>       </tr>       </table>     $des     </div>     ";   }   else   {    echo "    <div id='message'>     You must have a product id.    </div>    ";   }   mysql_close($con); ?> and the page for functions <?php defined("pc") or die("no direct access allowed");   function add_to_cart($id)   {     echo "     <form method='get'>       <input type='hidden' value='view' name='viewcart' />       Quantity: <input type='text' name='qty' value='1' size='3' />       <input type='hidden' name='addproductid' value='$id' /> <br />       <INPUT TYPE='image' SRC='' HEIGHT='40' BORDER='0' ALT='Submit Form'>     </form>     ";   } ?>  and you would need a page that allows people create items, but i dont feel that that is really relavant to this question.  I wouldnt use any of this code becuase its not finished and i know there are several flaws and security issues, but if you want to analyze it and see how it works go for it. Also you can find the whole thing here http://dev.bytecannon.net however that site is what i use to create all of the scripts and its not quite ready for launch. so i wouldnt use any of the scripts in there.   Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914475 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 couldnt a use of a flat file database be used, cause i cant use mysql on my hosting.. Â Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914543 Share on other sites More sharing options...
dave_sticky Posted September 8, 2009 Share Posted September 8, 2009 Yep, flat-file could be used if needed. Bit more complicated to set up and access though. Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914556 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 guess ill give it a shot Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914561 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 Well i thought i could start by producing the arrays  would i then be able to use this code <?php //These bunch of arrays act as a database. $categories=array(); $categories[]='Socks'; $categories[]='Shoes'; $catergories[]='Ball'; $products=array(); $products['item1']['category']='socks1'; $products['item1']['sizes']='0,1,2,3,4'; $products['item1']['price']='2'; $products['item1']['category']='shoe1'; $products['item1']['sizes']='0,1,2,3,4'; $products['item1']['price']='3'; $products['item1']['category']='ball1'; $products['item1']['sizes']='0,1,2,3,4'; $products['item1']['price']='4'; ?>  to act as a database? Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914568 Share on other sites More sharing options...
dave_sticky Posted September 8, 2009 Share Posted September 8, 2009 Theoretically yes, you could do it like this, but this will put a lot of processing on each page... Particularly if you've got a large shop - every time a page loads, the whole shop will load (behind the scenes) just to pull out the one item that needs to appear on the page. Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914582 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 i have absolute no idea how to do it. well there is going to be about 6 items. The only problem is that i can write a database driven shopping cart. But get completly stuck when using arrays this way. Do you have a different way it can be done? Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914590 Share on other sites More sharing options...
dave_sticky Posted September 8, 2009 Share Posted September 8, 2009 Well as it is only 6 items, and in the absence of MySQL, I'd probably go with a static page for each item, and the code (or a modification of it) that I posted yesterday for the shopping cart. It would be by far the quickest way of implementing it. It will of course mean that it isn't very scalable - a new item would require a new file. Â Or alternately, get a server with MySQL on it! Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914597 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 Thanks for your help dave, ill keep you posted. So you think i shouldnt store my arrays like i have and just do it the way you have correct ? Â ill give it a go! cheers Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914695 Share on other sites More sharing options...
dave_sticky Posted September 8, 2009 Share Posted September 8, 2009 Well it's up to you, but personally I would use static pages to do it... Â Good luck with it! Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914711 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 <a href='<?PHP echo $_SERVER['REQUEST_URI']; ?>&action=add_to_cart&item=ItemName'>Add To Cart Link</a> Â im having problems with this line of code. Do i have to define Item? Â as the items i have stored? Â <?php error_reporting(E_ALL); ini_set('display_errors', '1'); session_start(); $_SESSION['shopping_cart'] = array(); // And then to add items... $_SESSION['shopping_cart'][] = "Ball"; $_SESSION['shopping_cart'][] = "Shoe"; // And to echo them back out... foreach($_SESSION['shopping_cart'] as $value) { Â echo $value . "<br />"; } ?> <html> <head> </head> <body> <a href='<?PHP echo $_SERVER['REQUEST_URI']; ?>&action=add_to_cart&item=Ball'>Add To Cart Link</a> </body> <?php if($_GET['action'] == "add_to_cart") { Â $_SESSION['shopping_cart'][] = $_GET['item']; } ?> <?php foreach($_SESSION['shopping_cart'] as $key => $value) { echo $value . "<a href='" . $_SERVER['REQUEST_URI'] . "&action=remove_item&itemkey=" . $key ."'>Remove</a>"; } if($_GET['action'] == "remove_item") { unset($_SESSION['shopping_cart'][$_GET['itemkey']]); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914717 Share on other sites More sharing options...
dave_sticky Posted September 8, 2009 Share Posted September 8, 2009 Um... I don't know what your URL looks like, but if you're not using dynamic URLs (like index.php?page=page1 (or whatever)) you'll want to change the first & to a question mark  <a href='<?PHP echo $_SERVER['REQUEST_URI']; ?>?action=add_to_cart&item=Ball'>Add To Cart Link</a> When you say "problems"... does it give you an error message? Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914730 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 the problem is that when i click the link i get Object not found! Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914734 Share on other sites More sharing options...
TheJoey Posted September 8, 2009 Author Share Posted September 8, 2009 never mind the ? fixed the issue. Just gotta play around with what i got. Thanks for your help dave your a legend man. Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914736 Share on other sites More sharing options...
dave_sticky Posted September 8, 2009 Share Posted September 8, 2009 Ok, no probs mate. Glad to be of help. Â By the way, I was just tinkering with it on my local server... Probably best to use $_SERVER['PHP_SELF'] and not $_SERVER['REQUEST_URI'] if you're not using dynamic URLs... Otherwise you'll wind up with a very long url very quickly. Â If you are using dynamic URLs, you'll need to find some way of cleaning the link before echoing it out. Â Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914750 Share on other sites More sharing options...
dave_sticky Posted September 8, 2009 Share Posted September 8, 2009 By the way, unless you've spotted this problem already you're going to have a whole world of issues with the shopping cart emptying / adding things to itself every time the page reloads. I'm going offline for the day soon, so if you get stuck, this should help: Â <?php error_reporting(E_ALL); ini_set('display_errors', '1'); session_start(); if(!isset($_SESSION['shopping_cart'])) { Â $_SESSION['shopping_cart'] = array(); } // And then to add items... // $_SESSION['shopping_cart'][] = "Ball"; // $_SESSION['shopping_cart'][] = "Shoe"; // Adding to Cart: if(isset($_GET['action']) && $_GET['action'] == "add_to_cart") { Â $_SESSION['shopping_cart'][] = $_GET['item']; } // Removing From Cart: if(isset($_GET['action']) && $_GET['action'] == "remove_item") { Â unset($_SESSION['shopping_cart'][$_GET['itemkey']]); } ?> <html> <head> </head> <body> <?PHP Â Â echo "<b>Shopping Cart</b><br />"; Â Â foreach($_SESSION['shopping_cart'] as $key => $value) { echo $value . " <a href='" . $_SERVER['PHP_SELF'] . "?action=remove_item&itemkey=" . $key ."'>Remove</a><br />"; Â } Â ?> <br /> <br /> <a href='<?PHP echo $_SERVER['PHP_SELF']; ?>?action=add_to_cart&item=Ball'>Add Ball to Cart</a><br /> <a href='<?PHP echo $_SERVER['PHP_SELF']; ?>?action=add_to_cart&item=Shoe'>Add Shoes to Cart</a> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-914767 Share on other sites More sharing options...
TheJoey Posted September 10, 2009 Author Share Posted September 10, 2009 yeah i was having a world of trouble with the session and url. thanks dave. Quote Link to comment https://forums.phpfreaks.com/topic/173422-solved-php-shopping-cart-that-uses-arrays/#findComment-916128 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.