I am starting in php and I occupy shopping cart with sessions, I show the products through the database with a while and in each while there is a button with the id of the product and when I click on the button , calls a function of js where it receives the id and the pieces and then sends them to another function that uses ajax to send all the data to a php file where I create an array where I keep all the data of the product id, name, price etc then that array I keep in a session "orders" with a subindice equal to the id of the product, the problem is that when I give in add to a product that is not the first one shown, it does not send it, but if it works with the first product shown, I do not know what to do the truth I searched but nothing I give, I leave the code attached
Here I show the products and the button performs the function of js
<?php
foreach ($resultado as $registros) {
$datos=$registros['ID_PRODUCTO'];
?>
<li>
<img class="imagenesproductos"src="<?php echo
$registros['DIRECCION_IMAGEN']; ?>" alt="">
<h1><?php echo $registros['DESCRIPCION'] ;?></h1>
<p class="precio">PRECIO: <?php echo $registros['PRECIO']; ?> </p>
<p class="descripcion"><?php echo $registros['descripcion_producto'] ;?>
</p>
<p>Piezas:<p>
<input type="number" name="piezas" id="piezas" min="0" checked
placeholder="Numeros de piezas">
<input type="hidden" id="id_producto" name="" value="<?php echo $datos;?
>">
<input type="submit" name="" value="">
<button type="button" onclick="productos()" name="agregar" id="agregarp"
value="" >Agregar</button>
</li>
<?php
}
?>
in the function I rescue the values of the product and the selected pieces and I send them to another function that is responsible for sending it to a php file
function productos(){
id=$('#id_producto').val();
piezas=$('#piezas').val();
agregarpedido(id,piezas);
}
function with ajax
function agregarpedido(id,piezas){
cadena="id=" + id +
"&piezas=" + piezas
$.ajax({
type:"POST",
url:"../php/pedidos.php",
data:cadena,
success:function(respuesta){
alertify.success("Producto agregado");
}
});
}
php file here I create sessions and I keep the records in session
<?php
require_once('../funciones/bd_conexion.php');
session_start();
$pedidos=array();
if (isset($_SESSION['pedidos']))
$pedidos=$_SESSION['pedidos'];
}
$id_producto=$_POST['id'];
$sql=("SELECT * FROM producto where ID_PRODUCTO ='$id_producto' ");
$resultado=$conn->query($sql);
$registros=$resultado->fetch_assoc();
$item=array(
'id'=>$id_producto,
'producto'=>$registros['DESCRIPCION'],
'precio'=>$registros['PRECIO'],
'piezas'=>$_POST['piezas']
);
if (!empty($pedidos)) {
foreach ($pedidos as $recorrido) {
if ($recorrido['id']==$id_producto) {
$item['piezas']=$recorrido['piezas'] + $item['piezas'];
}
}
}
$item['subtotal']=$item['precio'] * $item['piezas'];;
$_SESSION['pedidos'][$id_producto]=$item;
?>