mattspriggs28 Posted May 24, 2010 Share Posted May 24, 2010 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 More sharing options...
hamza Posted May 24, 2010 Share Posted May 24, 2010 when u r going to creat a cookie make sure few thing and keep in mind nothing is outputing to browser and no empty or extra line output before cookie creation. and it is prefered to place cookie creationg code in page head tag. i had red this so many places// Link to comment https://forums.phpfreaks.com/topic/202721-cookies-not-setting-first-time-around/#findComment-1062570 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.