0

I want to use sessions to count how many items are added to the cart. Below I have a submit button that pulls product_id from database along with title and description:

$query = 'SELECT * FROM products ORDER BY date_added DESC'; 

    // Run the query:
    if($r = mysql_query($query,$dbc)) {
        while ($row = mysql_fetch_array($r)) {   
            // Print out the returned results:
            print "<p><h3>{$row['title']}</h3> {$row['description']}<br />
                <form action='add_to_cart.php' method='get'>
                    <input type='hidden' name='add2cart' value='{$row['product_id']}' />
                    <input type='submit' value='Add to Cart' />
                </form>
           </p><hr />\n";
        }     
    }

How do I turn the below into a session to handle my form when add to cart button is submitted. This script I created just counts the cookie every time the page is called or refreshed so it is not accurate. I want to send unique product id and add item to cart using sessions so the items in cart only go up when the add to cart button is clicked.

<?php
if(!isset($_COOKIE['countItems'])){
    $Items = 0;
    setcookie('countItems', $Items); 
}
else{
    $Items = ++$_COOKIE['countItems'];  
    setcookie("countItems", $Items);
} 
define('TITLE' , 'Items in cart'); 
include('templates/header.html');
?>
<div id="main">
<?php
require_once('config.php');
$dbc = mysql_connect(DB_HOST , DB_USER , DB_PASSWORD);
mysql_select_db(DB_DATABASE, $dbc);


if(isset($_COOKIE['countItems'])){
    print "<p>You have $Items items in your shopping cart </p>";
    print "<p><a href='store.php'>Continue Shopping</a></p>";
}  
else{
    print "You have not added any items into your cart.";
}  

?> 

I just need it to output what you see, it doesn't need to be a itemized or anything, just needs to count how many items are in cart and what there ids are.

2
  • Why do you need to work with cookies? You can session_start and then use $_SESSION. Commented May 11, 2012 at 0:11
  • I am new to php, sorry if I phrased that wrong. I don't need cookies, I am trying to rewrite to use sessions instead because cookies will not work with what I am trying to do. The above code is what I tried with no avail. Commented May 11, 2012 at 0:44

1 Answer 1

1
session_start();
if (! isset($_SESSION['countItems']))$_SESSION['countItems'] = 0;
else $_SESSION['countItems']++;
$Items = $_SESSION['countItems'];

then continue with define('TITLE' , 'Items in cart');

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.