Answer the question
In order to leave comments, you need to log in
How to calculate the quantity and display the amount (basket class + cookies)?
I recently switched to OOP and am making a shopping cart for the site. I found a basket here - Basket
I'm not very familiar with cookies yet and in general with OOP. But I want to understand.
There is a class Cart in which there are 2 methods responsible for products
public function getItems($for_sql = false)
{
if ($for_sql) {
return implode(',', $this->items);
}
return $this->items;
}
public function addItem($id)
{
$id = (int)$id;
$key = array_search($id, $this->items);
if (!in_array($id, $this->items)) {
array_push($this->items, $id);
}
Cookie::set('items', serialize($this->items));
}
echo "My cart: <br>";
foreach ($items as $items) {
echo "<b>{$items['name']}</b> | Количество " .count($items['id']). " | <a href='cart.php?action=delete&id={$items['id']}'>Удалить из корзины</a><br>";
Answer the question
In order to leave comments, you need to log in
Why ajax, cookies, etc.? Extra requests to the server, the problem of disabled cookies. Maybe it's better to use localStorage?
https://www.w3schools.com/html/html5_webstorage.asp
Everything is client side, the server smiles.
Now according to your code: count($items['id'])
- I doubt very much that there is any sense in this. In any case, to help you need to see the architecture of the array. Do <pre><?php print_r($items)?></pre>
and add the result to the question.
In short, the author of this "basket" is an idiot.
Nobody makes baskets like that.
Run from this site wherever your eyes look. This "devionity" is even worse than Popov's video courses.
The basket should contain only unique products, and the quantity is written in a separate field.
if (isset($this->products[$id])) {
$this->products[$id] = 1;
} else
$this->products[$id]++;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question