Jump to content

Recommended Posts

I finished getting the shopping cart organize.  Every time i refresh the page (under the shopping_cart.php) an addition quantity is added by increment of 1 (changing the final price as well).  How do I stop this from happening?

 

shopping_cart.php

<?php
// Include functions
require_once('inc/functions.inc.php');

// Start the session
session_start();

// Process actions
$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action) {
case 'add':
	if ($cart) {
		$cart .= ','.$_GET['id'];
	} else {
		$cart = $_GET['id'];
	}
	break;		
case 'delete':
	if ($cart) {
		$items = explode(',',$cart);
		$newcart = '';
		foreach ($items as $item) {
			if ($_GET['id'] != $item) {
				if ($newcart != '') {
					$newcart .= ','.$item;
				} else {
					$newcart = $item;
				}
			}
		}
		$cart = $newcart;
	}
	break;
case 'update':
if ($cart) {
	$newcart = '';
	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;
break;
}
$_SESSION['cart'] = $cart;
?>

 

functions.inc.php

<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
	return '<p>You have no items in your shopping cart</p>';
} else {
	// Parse the cart session variable
	$items = explode(',',$cart);
	$s = (count($items) > 1) ? 's':'';
	return '<p>Shopping Cart <a href="shopping_cart.php">'.count($items).' item'.$s.' </a></p>';
}
}

function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
	$items = explode(',',$cart);
	$contents = array();
	foreach ($items as $item) {
		$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
	}

	$output[] = '<form action="shopping_cart.php?action=update" method="post" id="cart">';
	$output[] = '<table border="0" width="100%" cellspacing="0" cellpadding="0">';
	foreach ($contents as $id=>$qty) {
		$sql = 'SELECT * FROM Products WHERE id = '.$id;
		$result = $db->query($sql);
		$row = $result->fetch();
		extract($row);

        $output[] = '<tr>';        
            	$output[] = '<td width="217" align="center">
					<a class="right_20" href="product_info.php?products_id='.$id.'">
					<img src="images/product_5.jpg" alt="Consectetur adipiscing" title="Consectetur adipiscing" 
					width="211" height="211" /></a></td>';
			$total += $price * $qty;		
			$output[] = '<td width="414" valign="top"><a href="product_info.php?products_id='.$id.'">
					<strong>Consectetur adipiscing</strong></a>
    					<span class="markProductOutOfStock">***</span><br /><br />
					<input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" />
                    	<div><button type="submit">Update cart</button> or 
					<a href="shopping_cart.php?action=delete&id='.$id.'" class="r">Remove</a></div></td>';
			$output[] = '<td width="207" align="right" valign="top"> <strong>$'.($price * $qty).'</strong></td>';
	$output[] = '</tr>'; 


	}
	$output[] = '<tr>';	
			$output[] = '<td colspan="2"></td>';
			$output[] = '<td ><p align="right">Grand total: <strong>$'.$total.'</strong></p></td>';
	$output[] = '</tr>'; 
	$output[] = '<tr>';
			$output[] = '<td colspan="3"><p class="stockWarning" align="center">Products marked with *** dont 	
						exist in desired quantity in our stock.<br />You can buy them anyway and check the 
						quantity we have in stock for immediate deliver in the checkout process.</p></td>';
	$output[] = '</tr>';
	$output[] = '</table>';
	$output[] = '</form>';

} else {
	$output[] = '<p><a href="products_new.php">Continue Shopping</a></p>';
}
return join('',$output);

}
?>

 

 

Link to comment
https://forums.phpfreaks.com/topic/268105-shopping-cart-refresh-issue/
Share on other sites

I finished getting the shopping cart organize.  Every time i refresh the page (under the shopping_cart.php) an addition quantity is added by increment of 1 (changing the final price as well).  How do I stop this from happening?

 

shopping_cart.php

<?php
// Include functions
require_once('inc/functions.inc.php');

// Start the session
session_start();

// Process actions
$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action) {
case 'add':
	if ($cart) {
		$cart .= ','.$_GET['id'];
	} else {
		$cart = $_GET['id'];
	}
	break;		
case 'delete':
	if ($cart) {
		$items = explode(',',$cart);
		$newcart = '';
		foreach ($items as $item) {
			if ($_GET['id'] != $item) {
				if ($newcart != '') {
					$newcart .= ','.$item;
				} else {
					$newcart = $item;
				}
			}
		}
		$cart = $newcart;
	}
	break;
case 'update':
if ($cart) {
	$newcart = '';
	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;
break;
}
$_SESSION['cart'] = $cart;
?>

 

functions.inc.php

<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
	return '<p>You have no items in your shopping cart</p>';
} else {
	// Parse the cart session variable
	$items = explode(',',$cart);
	$s = (count($items) > 1) ? 's':'';
	return '<p>Shopping Cart <a href="shopping_cart.php">'.count($items).' item'.$s.' </a></p>';
}
}

function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
	$items = explode(',',$cart);
	$contents = array();
	foreach ($items as $item) {
		$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
	}

	$output[] = '<form action="shopping_cart.php?action=update" method="post" id="cart">';
	$output[] = '<table border="0" width="100%" cellspacing="0" cellpadding="0">';
	foreach ($contents as $id=>$qty) {
		$sql = 'SELECT * FROM Products WHERE id = '.$id;
		$result = $db->query($sql);
		$row = $result->fetch();
		extract($row);

        $output[] = '<tr>';        
            	$output[] = '<td width="217" align="center">
					<a class="right_20" href="product_info.php?products_id='.$id.'">
					<img src="images/product_5.jpg" alt="Consectetur adipiscing" title="Consectetur adipiscing" 
					width="211" height="211" /></a></td>';
			$total += $price * $qty;		
			$output[] = '<td width="414" valign="top"><a href="product_info.php?products_id='.$id.'">
					<strong>Consectetur adipiscing</strong></a>
    					<span class="markProductOutOfStock">***</span><br /><br />
					<input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" />
                    	<div><button type="submit">Update cart</button> or 
					<a href="shopping_cart.php?action=delete&id='.$id.'" class="r">Remove</a></div></td>';
			$output[] = '<td width="207" align="right" valign="top"> <strong>$'.($price * $qty).'</strong></td>';
	$output[] = '</tr>'; 


	}
	$output[] = '<tr>';	
			$output[] = '<td colspan="2"></td>';
			$output[] = '<td ><p align="right">Grand total: <strong>$'.$total.'</strong></p></td>';
	$output[] = '</tr>'; 
	$output[] = '<tr>';
			$output[] = '<td colspan="3"><p class="stockWarning" align="center">Products marked with *** dont 	
						exist in desired quantity in our stock.<br />You can buy them anyway and check the 
						quantity we have in stock for immediate deliver in the checkout process.</p></td>';
	$output[] = '</tr>';
	$output[] = '</table>';
	$output[] = '</form>';

} else {
	$output[] = '<p><a href="products_new.php">Continue Shopping</a></p>';
}
return join('',$output);

}
?>

First of all...

$cart = $_SESSION['cart'];

You must check if the variables you use are set. isset()

Don't assume they exist when you haven't just set them yourself.

 

		foreach ($_POST as $key=>$value) {
		if (stristr($key,'qty')) {

Why do you need to do stristr through all $_POST data?

Can't they all the products be put in it's own array when sent as $_POST data, so you can foreach those.

The name in the form inputs: "product[id][name]" and "product[id][quantity]"

 

I can't see when you use those two included functions.

		foreach ($_POST as $key=>$value) {
		if (stristr($key,'qty')) {
			$id = str_replace('qty','',$key);
			$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);

What does variables in $_POST that contains the 'qty' in their keyname contain? Just a little confused about it, as I would think it contained how many there is of a product they want to update.

 

 

		foreach ($contents as $id=>$qty) {
		$sql = 'SELECT * FROM Products WHERE id = '.$id;

Security hole, because the $id is provided by the client.

 

 

Another thing I don't get is why you keep writing arrays to string and then back to arrays and then to string and then array etc >_> So hard to read and so unnecessary.

 

Here's your problem:

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

More precisely here:

for ($i=1;$i<=$value;$i++) {

 

change it to:

for ($i=1;$i<$value;$i++) {

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.