Jump to content

[SOLVED] PHP shopping cart that uses arrays?


TheJoey

Recommended Posts

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 />";
}

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

<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']]);
}
?>

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

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

Join the conversation

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

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

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

×   Your previous content has been restored.   Clear editor

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

×
×
  • Create New...

Important Information

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