My problem is that I created a cart shop of products that are saved in a database, then I created a while
to print the info of the product (name, genre, price) and next of them the quantity of products one want to buy.
The problem is that only reads one of the multiple inputs created and calculate with that quantity instead of every one the created ones. So I am glad if you can help my in fix the part of the code that is causing the problem.
Sorry if something is unclear, it is my first post here.
Here are the codes.
The PHP file that prints the info:
<tbody>
<tr>
<?php
$conexion = mysqli_connect("localhost", "root", "", "llanoponte");
$sql = "SELECT * FROM libros";
$resultado = $conexion->query($sql);
$x = 0;
if ($resultado->num_rows > 0) {
while ($row = $resultado->fetch_assoc()) {
$valor = $row['Precio'];
echo "<td>", $row['Titulo'], "</td>
<td>", $row['Autor'], "</td>
<td>", $row['Genero'], "</td>
<td>", $valor, " €", "</td>
<td>", "<input type='number' name='cantidad' class='cantidad' value='0' id='<?php echo $x ?>'>", "</td>
</tr>";
$x++;
}
} else {
echo "Sin resultados";
}
$conexion->close();
?>
</tr>
</tbody>
Here is the button to call the function
<input type="button" name="actualizar" class="calcular" onclick="Datos()" id="boton1" value="Calcular">
The script that sends the inserted quantity to the PHP file that makes the operation:
function Datos() {
v1 = $("input[name='cantidad']").val();
$.ajax({
url: 'total.php',
type: 'post',
data: {cantidad: v1},
success: function (respuesta) {
$('#resultados').html(respuesta);
}
})
}
The PHP that calculates the total and return the value to the principal:
include('conexiones.php');
$multi1 = $_POST['cantidad'];
$conexion = mysqli_connect("localhost", "root", "", "llanoponte");
$sql = "SELECT * FROM libros";
$resultado = $conexion->query($sql);
if ($resultado->num_rows > 0) {
$total = 0;
while ($row = $resultado->fetch_assoc()) {
$total = ($row['Precio'] * $multi1) + $total;
}
echo '<p>', $total, ' € ', '</p>';
} else {
echo 'Sin resultados';
}
$conexion->close();
And this is where the total of price should appear
<div class="texto2">
<h1>Total</h1>
<div id="resultados">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</div>
</div
I tried change the IDs to an element whose value will increase by every loop of the while loop but then I faced with the obstacle of send the inputs and their values to the other PHP through the script. And even trying to change from obtaining the value from element with certain id to name, it still captures the value of the first input created and not the rest.