I am trying to assign attributes to certain products, in special cases such as clothing, shoes, among other items, where size and color must be included, I have done the following by adding color
and size
:
<?php
if (isset($_POST)) {
$itemId = isset($_POST['itemId']) ? $_POST['itemId'] : "";
$item_color = isset($_POST['color']) ? $_POST['color'] : "";
$item_size = isset($_POST['size']) ? $_POST['size'] : "";
if (is_numeric($itemId)) {
$limit_data = 1;
$stmt = $con->prepare("SELECT id_product, type_product, title_product, price_old, price FROM tbl_products WHERE id_product=? LIMIT ?");
$stmt->bind_param("ii", $itemId, $limit_data);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result(
$id_product,
$type_product,
$title_product,
$price_old,
$price
);
$stmt->fetch();
$stmt->close();
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['qtyupdate'])) {
for ($i = 0; $i < count($_POST['qtyupdate']); $i++) {
$key = $_POST['arr_key_' . $i]; //arr_key_0, arr_key_1, arr_key_2
$_SESSION['qty'][$key] = $_POST['qtyupdate'][$i];
}
} else {
//Add new register in base session
$qty = isset($_POST['qty']) ? $_POST['qty'] : 1;
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'][] = array(
'id_product' => $id_product,
'title_product' => $title_product,
'price_old' => $price_old,
'price' => $price,
'qty' => $qty,
'color' => $item_color,
'size' => $item_size
);
$_SESSION['qty'][] = array();
}
if ($type_product === "digital") {
if(!in_array($itemId, $_SESSION['cart'])){
array_push($_SESSION['cart'], $itemId);
$key = array_search($itemId, $_SESSION['cart']);
$_SESSION['qty'][$key] = $qty;
echo json_encode(['status'=> TRUE, 'message'=>"<strong>El producto ha sido añadido a su carrito.</strong>"]);
exit;
} else {
echo json_encode(['status'=> FALSE, 'message'=>"<strong>Este producto ya está añadido al carrito.</strong>"]);
exit;
}
} else {
if (in_array($itemId, $_SESSION['cart'])) {
//The product already added to the shopping cart is updated +1
$key = array_search($itemId, $_SESSION['cart']);
$_SESSION['qty'][$key] = $_SESSION['qty'][$key] + $qty;
echo json_encode(['status'=> TRUE, 'message'=>"<strong>Se ha actualizado su producto +1.</strong>"]);
exit;
} else {
//The product is added to the shopping cart for the first time
array_push($_SESSION['cart'], $itemId);
$key = array_search($itemId, $_SESSION['cart']);
$_SESSION['qty'][$key] = $qty;
echo json_encode(['status'=> TRUE, 'message'=>"<strong>El producto ha sido añadido a su carrito.</strong>"]);
exit;
}
}
}
} else {
echo json_encode(['status'=> FALSE, 'message'=>"<strong>Error, producto no encontrado.</strong>"]);
exit;
}
}
?>
But when printing the data print_r($_SESSION['cart']);
it shows me this result:
Array
(
[0] => 1
)
It should print something like this:
Array
(
[0] => Array
(
[id_product] => 1
[title_product] => prueba
[price_old] => 12
[price] => 10
[qty] => 1
[color] => amarillo
[size] => L
)
)
The idea of this is to be able to then print said data in the shopping cart and list it as follows, as can be seen in the cart to print the result should reflect the same product but in case the data is different this it should be duplicated as if it were a different product:
Item Size Color Price Quantity Subtotal
prueba L red 5.00 2 10.00
prueba M red 5.00 3 15.00
prueba XL red 5.00 1 5.00
prueba XL black 5.00 1 5.00
This is the code that will list the result in the shopping cart, of course it should be modified here since this way the product will not be duplicated when the values are different, I think that here I should use a foreach
instead of query data and print with the while
:
<?php
session_start();
$items = (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) ? $_SESSION['cart'] : array();
$itemCount = count($items);
$qty = (isset($_SESSION['qty']) && is_array($_SESSION['qty'])) ? $_SESSION['qty'] : array();
$couponDiscount = (isset($_SESSION['couponCode']));
$total = 0;
$num = 1;
$meQty = 0;
$itemId = "";
$meCount = $itemCount;
foreach ($qty as $id_product => $valueqty) {
//$meQty = $meQty + $valueqty;
$meQty = (is_numeric($valueqty)) ? ($meQty + $valueqty ) : ($meQty +0);
}
foreach ($items as $id_product => $item) {
$itemId = $itemId . $item . ",";
}
$array = explode(',', $itemId);
$strMarcas = str_repeat('?,', count($array) - 1) . '?';
$strTipos = str_repeat('i', count($array));
$stmt = $con->prepare("SELECT id_product, title_product, subtitle_product, price_old, price FROM tbl_products WHERE id_product in ($strMarcas)");
$stmt->bind_param($strTipos, ...$array);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id_product, $title_product, $subtitle_product, $price_old, $price);
$get_coupon = isset($_GET['couponCode']) ? $_GET['couponCode'] : '';
while ($stmt->fetch()) {
$key = array_search($id_product, $items);
$total = $total + $price * $qty[$key];
?>
<div class="items relative">
<div class="bsk-item flex">
<div class="timg">
<img src="https://i...content-available-to-author-only...g.com/vi/ZxrUVuOqsy0/maxresdefault.jpg">
</div>
<div class="heading bsk ellipsis"><p><?php echo $title_product; ?></p></div>
</div>
<div class="bsk-price">$<?php echo number_format($price,2); ?></div>
<div class="bsk-quantity"><?php echo $qty[$key]; ?></div>
<div class="bsk-subtotal">$<?php echo number_format(($price * $qty[$key]),2); ?></div>
<div class="delete">
<span title="Eliminar" class="removeCart" id="<?php echo $id_product; ?>">
<i class="icon-delete"></i>
</span>
</div>
</div>
<?php
}
$stmt->close();
?>
And, this is my ajax code https://jsfiddle.net/5k381gy4/ using the following I add the product to the cart:
<span title="Añadir al carrito" class="addCart buy" id="1">Añadir a la cesta</span>
With the new attributes I am forced to use the same ajax but sending data through a given to the new attributes of type form
fields that I am going to use for the theme of and size .input
radio
color
size
The structure of the database or data table, I am only using a simple table, it is composed ofid_product, title_product, subtitle_product, price_old, price
What am I doing wrong? If I am addingsession_start();
At first I thought that the problem would be the call to:
but in this case it would print
Therefore the code that displays the value of the array should be as you describe:
The only way to get the value you indicate is that you are modifying it at some other point, for example:
would get:
You have a bit of a mess in logic, because you don't previously create the array and insert the product, but only the first one, because the following times, it no longer enters this block:
Later, you insert again, but only ID:
So the first product in the cart should have the desired structure, but the others will only have IDs.
Possible solution:
The first thing you need to do is check that the variable exists in session, otherwise create it:
It is also convenient to create an array to return the result and you are going to update it according to the result:
The variable
$_POST
always exists, although if it is empty itisset($_POST)
will return false; however, it is recommended to verify that the element to search for exists:Instead of handling the
cart
y variablesqty
within the session, I suggest you store the quantity in the corresponding element and additionally assign product ID as the array index.For now, if
$itemId
it is not numeric, you will not be able to update the quantity here, that must be passed at the end.It seems that you send an array to update the quantity of all the products in the cart and it must be handled separately. It only remains to see your HTML to know what changes must be made:
At the end of the script you send the variable
$res
:Note: Don't copy the code because I have no way to test it; try to understand how it works and only then update your script.