I have an cookie array with json items like this
//set my cookie
setcookie("my_Cookie", $cookie_content, time()+3600);
//this is the content of my cookie for example with 2 items
[{"item_id":"9","item_tag":"AS","session_id":"554obe5dogsbm6l4o9rmfif4o5"},{"item_id":"6","item_tag":"TE","session_id":"554obe5dogsbm6l4o9rmfif4o5"}]
The workflow is like an shopping cart, I can add and delete items. One "product" on my website contains: item_id, item_tag and the session_id;
For adding an item the cookie will be extended with item_id":"X","item_tag":"X","session_id":"X
now if I click on delete I want remove the current three values in the cookie
I try it with
unset($_COOKIE["my_Cookie", 'item_id'=> $item_id, 'item_tag'=> $item_tag, 'session_id'=> $session_id]); but this doesn't work
Is it possible to delete specific values of my cookie?
Like this:
setcookie('cookie_name'); // Deletes the cookie named 'cookie_name'.
This works because setting a cookie with no value is the same as deleting it.
If I'm not mistaken, you can't directly modify a cookie's value; you'll have to read the value, make any modifications, and then replace the cookie using the same name.
So, in this case, once a user hits the delete link, your script should save the ID of the item that they want removed, read the cookie value(s), rewrite the array and then replace the cookie with the updated values.
Perhaps this demo will help:
// Should be the user submitted value to delete.
// Perhaps a $_GET or $_POST value check.
$value_to_delete = 9;
// Should be the cookie value from $_COOKIE['myCookie'] or whatever the name is.
// Decode from JSON values if needed with json_decode().
$cookie_items = array(
array("item_id" => 9, "item_tag" => "RN"),
array("item_id" => 6, "item_tag" => "RN"),
array("item_id" => 4, "item_tag" => "RN")
);
// Run through each item in the cart
foreach($cookie_items as $index => $value)
{
$key = array_search($value_to_delete, $value);
if($key == "item_id")
{
unset($cookie_items[$index]);
}
}
// Reset the index
$cookie_items = array_values($cookie_items);
// Set the cookie
setcookie($cookie_items);
// Debug to view the set values in the cookie
print_r($cookie_items);
I believe a cookie will simply be stored as a string so you might be best off just overwriting it...
Related
Not sure how to title this properly but here's the issue I am running into currently. I built a cart and checkout system and it loads all the data into a database when it finalized the order. To save some space, I stored just the item IDs originally but then I ran into the issue of if I deleted the item from the database (because it was discontinued or whatever) then it wouldn't return the info I needed. And if they ordered more then 1 item the database record would be wrong. So I stored the data like so:
Itemid:Quantity:Price:name, itemid2:quantity2:price2:name2
OR
1:3:20.00:Flower Hat, 2:1:17.75:diamonds
The issue I have right now that I need help with is this. I need to seperate the four values into variables like $price, $item, $id, $ammount so I can display them on the order history page and I need to loop through all items on the array so I can print a row for each item with all four fields respective to that item.
I use strpos already to get the shipping info from the same database field which is formatted as METHOD:Price but since I have 3 :'s on my string I'm not sure how to go through each one. Thanks.
Here's a function
function parseItems($dbjunk){
$cart = array();
$items = explode(",",$dbjunk);
foreach($items as $i){
$chunks = explode(":", $i);
$cart[] = array(
"ItemID" => $chunks[0] ,
"Quantity" => $chunks[1] ,
"Price" => $chunks[2] ,
"name" => $chunks[3]
);
}
return $cart;
}
Example usage:
$dbjunk = "Itemid:Quantity:Price:name, itemid2:quantity2:price2:name2";
$parsed = parseItems($dbjunk);
print_r($parsed);
See: https://3v4l.org/rBkXF
If you need variables instead of an array you can use list(), like this..
$dbjunk = "Itemid:Quantity:Price:name, itemid2:quantity2:price2:name2";
$parsed = parseItems($dbjunk);
foreach($parsed as $p){
list($itemID, $Quantity, $Price, $name) = array_values($p);
var_dump($itemID, $Quantity, $Price, $name);
}
see: https://3v4l.org/l4vsn
You should not physically delete items from your database. Instead, put a new column named 'is_active' or something like that to indicate whether the product is active/non-deleted.
Answering your question, here is my suggestion:
$orderString = '1:3:20.00:Flower Hat, 2:1:17.75:diamonds';
$items = array();
foreach(explode(', ', $orderString) as $itemString) {
$itemData = explode(':', $itemString);
$items[] = array(
'id' => $itemData[0],
'amount' => $itemData[1],
'value' => $itemData[2],
'description' => $itemData[3]
);
}
with this code, you will obtain an array with the data of all the items in the string, no matter how much items are in the string
try something like
$data = 1:3:20.00:Flower Hat, 2:1:17.75:diamonds
list($price, $item, $uid, $id, $ammount) = explode(":", $data);
echo $user;
echo $item;
Read about First Normal Form. Basically, you want to store one value in one field. So, instead of this:
shipping = "method:price"
You want something like this:
shipping_method = "method"
shipping_price = "price"
Don't concern yourself with space -- it's essentially free nowadays.
Regarding your deleted items dilemma, your initial implementation was the way to go:
I stored just the item IDs originally
In addition to reverting to this technique, I would recommend two things:
Add a boolean field to your item table to represent if the item is currently available or not. This gives you the additional feature of being able to toggle items on/off without having to delete/insert records and change ids.
Before deleting an item, check to see if it's ever been ordered. If not, it's ok to delete. If so, instead just deactivate it.
I have a SESSION['cart'] with ID numbers only. I have a form passing the ID with a remove button. Once passed to my controller, I cannot figure out how to write the code that uses the ID ($_POST['id']) to delete the item from the SESSION['cart'].
I can loop through and display the array contents, but I cannot figure out how to delete based on ID passed from the form.
How do I loop through the SESSION['cart'] array to find a match with the ID passed from my delete form, and then delete that ID? I know that unset($_SESSION['cart'][X] deletes the ID at index X, but I cannot figure out how to loop through all the elements to find a match.
I have read a number of related issues in this forum but have been unable to apply any of those solutions to resolve this challenge. Any assistance is appreciated.
The way you have your values ($products = array(3,7,99,152)) isn't a very good method. Every time you want to perform an action, you have to loop through the array, you don't want that. Apart from that, how do you store quantity? Or variations like e.g. size or color?
if your structure is $array[ ID_OF_PRODUCT ], you can simply do this:
unset( $_SESSION['cart'][$_POST['id']] ); // Instant access via the key!
This should be the method to use. This allows you to create an array like this, with advanced info, but with easy access (42/63 are example id's)
$_SESSION['cart']['products'][42] = array(
'quantity' = 11,
'size' = 'large',
'color' = 'blue'
);
$_SESSION['cart']['products'][63] = array(
'quantity' = 9,
'size' = 'small',
'color' = 'red'
);
This way you can access a lot of info with the product ID, and now also see which size and color (both just examples) the user selected. You may not have need for this now, but you will further down the road :)
As you might see, you can easily do stuff with the item:
isset($_SESSION['cart'][$_POST['id']]); // check if the product exists
unset($_SESSION['cart'][$_POST['id']]); // remove the product
echo $_SESSION['cart'][$_POST['id']]['quantity']; // get the quantity.
Not a loop in the code. You should only use loops when you have to, try to somewhat avoid them because often their slow. Say you have an extreme case of 1000 items in your shop, and you need to delete no999... That'll take a noticable moment.
Here is the code to do it right:
$id = $_POST['id'];
$items = $_SESSION["cart"];
if(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
$_SESSION["cart"] = array_values($items);
Advice
Beside item ID, you can also sve item count in SESSION array because user can add several times same item into cart. In that case your $_SESSION["card"] should be structured like:
array(
'1'=>12,//Item with ID=1 is added 12 times in shopping cart
'17'=>2,//Item with ID=17 is added 2 times in shopping cart etc.
'32'=>12,
)
This one is really bugging me, and can not find a easy solution.
On a detail view of a product, i set the info to a session, maximum 4:
$_SESSION['recent'][] = array(
'id' => $productimgfolder,
'title' => $product['Product']['title'],
'link' => $_SERVER['REQUEST_URI'],
'image' => 'img/products/'.$productimgfolder.'/'.$product['Product']['mainpicture']
);
$_SESSION['recent'] = array_slice($_SESSION['recent'],-4);
This part works, if i output the session:
edit image => this is wat happens if i reload the detail view
The part i'am struggling with is, when i reload a detail view, the info in the session is duplicated.
How can i prevent this from happening?
I tried it with in_array & array_unique, i'am doing something wrong
The easy solution:
if the id is unique, you can do like this:
if(!array_key_exists ($productimgfolder, $_SESSION['recent']))
{
$_SESSION['recent'][$productimgfolder] = array(
'id' => $productimgfolder,
'title' => $product['Product']['title'],
'link' => $_SERVER['REQUEST_URI'],
'image' => 'img/products/'.$productimgfolder.'/'.$product['Product']['mainpicture']
);
}
$_SESSION['recent']=array_slice($arr, -4, 4, true);
other wise you have to foreach the recent array and check for id in the loop...
A different solution may be;
array_unshift($sessionArray, $singleArrayElement);
if (count($sessionArray) > 4) {
array_pop($seassionArray);
};
You need to check isset
if(!isset($_SESSION['recent']))
{
$_SESSION['recent'] = array()
}
THEN YOU CAN CHECK IF SESSION IS EMPTY
if(empty($_SESSION['recent']))
{
//here you add your data
}
because you are using array push, on page reload it adds data unless you check if session is empty. if yes you add data to your session.
I have an issue on how can I update my Previous array ?
What currently happening to my code is its just adding new session array instead of updating the declared key here's my code:
foreach ($items_updated as $key => $added)
{
if ($id == $added['item_id'])
{
$newquantity = $added['item_quantity'] - 1;
$update = array(
'item_id' => $items['item_id'],
'item_quantity' => $newquantity,
);
}
}
Session::push('items', $updated);
$items = Session::get('items', []);
foreach ($items as &$item) {
if ($item['item_id'] == $id) {
$item['item_quantity']--;
}
}
Session::set('items', $items);
If you have nested arrays inside your session array. You can use the following way to update the session: $session()->put('user.age',$age);
Example
Supppose you have following array structure inside your session
$user = [
"name" => "Joe",
"age" => 23
]
session()->put('user',$user);
//updating the age in session
session()->put('user.age',49);
if your session array is n-arrays deep then use the dot (.) followed by key names to reach to the nth value or array, like session->put('user.comments.likes',$likes)
I guess this will work for you if you are on laravel 5.0. But also note, that I haven't tested it on laravel 4.x, however, I expect the same result anyway:
//get the array of items (you will want to update) from the session variable
$old_items = \Session::get('items');
//create a new array item with the index or key of the item
//you will want to update, and make the changes you want to
//make on the old item array index.
//In this case I referred to the index or key as quantity to be
//a bit explicit
$new_item[$quantity] = $old_items[$quantity] - 1;
//merge the new array with the old one to make the necessary update
\Session::put('items',array_merge($old_items,$new_item));
You can use Session::forget('key'); to remove the previous array in session.
And use Session::push to add new items to Session.
I have a session var for a shopping cart that reads: 'cart_b_1_1'.
The letter in the string indicates a category, the ints represent user id & product id.
How can I check the category of an already set SESSION var to see if it matches the category of a new selection?
I am trying to make sure that if an item is added to the SESSION array and there is a var that already exists with the same category letter, then it is unset and effectively replaced with the new selection. This is to limit selections by category to one.
Thanks for the help in advance.
You should consider taking advantange of the awesomeness of what associative arrays let you do:
$_SESSION['categories'][$mycat] = array($user_id, $product_id);
That way whenever you set a new category it overrides the last one. Not sure why you need the user_id at that level, assuming the whole cart belongs to one user, my Session would look like:
array(
'user' => $user_id,
'cart' => array('catid' => 'prodid', 'catid2', 'prodid2'))
);
You should use 3 variables instead of 1.
$_SESSION['category'] = 'cart_b';
$_SESSION['user_id'] = 1;
$_SESSION['product_id'] = 1;
But just in general - you can convert string to a array with '_' separator.
$varArray = explode('_', $_SESSION['var']);
explode the session variable using _ and check the first element to find the category.
$myarray=explode("_",$_SESSION['yourvariablename']);
then you the $myarray[1] is the category so you can compare and do other stuff.
Is this what you wanted?