I'm developing an ecommerce site and as the shopping and checkout process for this site is quite complicated I am storing the contents of the shopping cart in a database.

When a visitor adds something to their cart my code (calling fnAddToCart) checks to see if the 'CartID' session variable is set and if not it inserts the user's IP address and some other data into the database and then reads back that identity of the last insert and this becomes the user's CartID.

If the CartID is already set then the item is just added to the same cart.

// Init cart
function fnInitCart(){
	session_start();

If(!isset($_SESSION['CartID'])) {
	session_register("CartID"); 

	$query = mysql_query("INSERT INTO tblorders (fldSessionID,fldIPAddress,fldUserAgent) VALUES ('". session_id() . "','" . $_SERVER['REMOTE_ADDR'] .  		"','" . $_SERVER['HTTP_USER_AGENT'] ."')") or die(mysql_error());
	$_SESSION['CartID'] = mysql_insert_id();


}
}

// Add to cart
function fnAddToCart($StockCode, $Qty, $ProductName, $Description, $Size, $Price, $CustomisationType){
	if ($Qty > 0){
		fnInitCart();

	$query = mysql_query("INSERT INTO tblorderitems (fldOrderID,fldStockCode, fldDescription, fldQtyOrder, fldUnitPrice, fldCustomisationType) VALUES ('". $_SESSION['CartID']. "','" .mysql_real_escape_string($StockCode)."', '".mysql_real_escape_string($ProductName)." ".mysql_real_escape_string($Description)." ".mysql_real_escape_string($Size)."', '".mysql_real_escape_string($Qty). "','" .mysql_real_escape_string($Price) . "','".$CustomisationType."')") or die(mysql_error());

}
}

This seems to work mostly but I have problems where if I return to the site after having closed my browser and been away for a few hours or if several users on the same LAN are all testing the site at once then sometimes you find items already in the cart which I would have thought shouldn't be there - almost like the session variable is remembered permanently or even being recalled sometimes for a different person connecting from a different PC but with the same IP address (that of our NAT router?)

I'm guessing that I am using sessions incorrectly somewhere or need the session to expire or something - Can anyone see any problem in my code or tell me where I am going wrong?

Thanks.

    Write a Reply...