Jump to content

Cookies not setting first time around


mattspriggs28

Recommended Posts

Hi,

 

I'm using cookies to set up a shopping cart to remember a basket id so that the items in the basket can be retrieved from the database.

 

The cookie (called 'basket') is set to 0 by default when a user visits the website, and then the cookie is assigned it's own basket id when the user first adds an item to their basket.

 

However, the problem I'm experiencing is that the first time a user adds an item, the cookie is not re-assigned its own value. The second time this is done it works fine.

 

I tried this without first assigning a default value of 0 for the cookie but this still causes the same problem.

 

Below is my code:

 

add.php (script used to create the basket and add the item selected to the basket

 

 

// Firstly, check if an order exists for this user
if (!Basket::CheckOrderExists()) {
if (!Basket::CreateNewOrder()){ // this is where the new basket id is assigned to the cookie
	header("Location: index.php");
}
}

if (Basket::AddBasketItem($_COOKIE['basket'], $_POST['form_prod_id'], $_POST['form_qty'])) {
header("Location: index.php?msg=itemadded");
}
else
{
header("Location: index.php?msg=erradding");	
}

 

Basket.class.php (class file with functions for creating/ adding to basket

 

function CheckOrderExists()
{
if (isset($_COOKIE["basket"]) && $_COOKIE["basket"] != 0)
{
	return true;
}
else
{
	return false;
}
}

function CreateNewOrder()
{
DbConnect::GetDatabaseConnection();

$sql = "Insert into *** (date_created, order_status) values (NOW() - INTERVAL 1 HOUR, 'BASKET')";
$res = mysql_query($sql);
$id = mysql_insert_id();

if ($res) {
	if (setcookie("basket", $id, time()+31536000, "/")) {
		return true;	
	}
	else {
		mysql_query("Delete from *** where id = ".$id);	
		return false;
	}
}

}

 

Any help is much appreciated.

Link to comment
https://forums.phpfreaks.com/topic/202721-cookies-not-setting-first-time-around/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.