Save orders in database

1

I have a cart and I am working on the button to confirm the purchase. The products arrive to the cart by means of a while, and I keep the data I need from each article in variables. The problem is that when doing the submit only print the values of my last article (I guess that is because the variable is overwritten) I need that if my cart has 2 products at the time of submit, I insert 2 rows in database . This is the while with which I show the selected products in cart:

$direct = "img/libros/";
                 $sql2 = "SELECT I.ISBN_id,I.titulo,I.imagen,I.precio,U.id,it.idOrdenes,it.libro,it.cantidad,it.usuario FROM lecturas_db.inventario I,lecturas_db.usuarios U,lecturas_db.items it WHERE U.id = it.usuario AND I.ISBN_id = it.libro AND it.usuario = $id";
				 $res = mysqli_query($conexion,$sql2);
                while($row = mysqli_fetch_array($res)) { ?>
                <form method="POST" class="Prod">
                <div>
                    <div class="imagenProd">
                        <img src="<?php echo $direct.$row['imagen'] ?>">
                    </div>
                    <div class="tituloProd">
                        <center><b><?php echo $row['titulo'] ?></b></center>
                    </div><br><br>
                    <div class="cantidadProd">
                        <center><b><?php echo $row['cantidad'] ?></b> unidad/es</center>
                    </div><br><br>
                    <div class="subtotalProd">
                        <center>Subtotal: <b>$<?php $subtotal = $row['precio']*$row['cantidad'];
                        echo $subtotal;
                        $total += $subtotal;
                        ?></b></center>	
                    </div><br><br>
                    <div class="eliminarProd">
						<input type="hidden" name="isbn" value="<?php echo $row['libro'] ?>">
						<input type="hidden" name="cantidadOrdenes" value="<?php echo $row['cantidad'] ?>">
						<input type="hidden" name="usuario" value="<?php echo $row['usuario'] ?>">
						<input type="hidden" name="precio" value="<?php echo $row['precio'] ?>">
						<input type="hidden" name="id" value="<?php echo $row['idOrdenes']?>">
                        <input type="submit" value="ELIMINAR" name="eliminar">
                    </div>
                </div><br><br>
                <?php if($_POST['eliminar']) {
						$id_eliminar = intval($_POST['id']);
                        $sql3 = "DELETE FROM lecturas_db.items WHERE idOrdenes = $id_eliminar LIMIT 1";
                        $res1 = mysqli_query($conexion,$sql3);
                        if($res1 > 0) {
                            echo "<script>
                            location.href='index.php';
                            </script>";
                        } else {
                            echo "nada";
                        } 
					} 
					$isbn = $row['libro'];
					$cantidadOrdenes = $row['cantidad'];
					$usuario = $row['usuario'];
					$precio = $row['precio']*$row['cantidad'];
					echo $isbn;
					echo $cantidadOrdenes;
					echo $usuario;
					echo $precio;
					?>
            </form>
				<?php } ?>
            <form method="POST" class="Prod">
            <div>
                <div class="imagenProd">
                    <img src="<?php echo $direct.$row['imagen'] ?>">
                </div>
                <div class="tituloProd">
                    <center><b><?php echo $row['titulo'] ?></b></center>
                </div><br><br>
                <div class="cantidadProd">
                    <center><b><?php echo $row['cantidad'] ?></b> unidad/es</center>
                </div><br><br>
                <div class="subtotalProd">
                    <center>Subtotal: <b>$<?php $subtotal = $row['precio']*$row['cantidad'];
                    echo $subtotal;
                    $total += $subtotal;
                    ?></b></center> 
                </div><br><br>
                <div class="eliminarProd">
                    <input type="hidden" name="isbn" value="<?php echo $row['libro'] ?>">
                    <input type="hidden" name="cantidadOrdenes" value="<?php echo $row['cantidad'] ?>">
                    <input type="hidden" name="usuario" value="<?php echo $row['usuario'] ?>">
                    <input type="hidden" name="precio" value="<?php echo $row['precio'] ?>">
                    <input type="hidden" name="id" value="<?php echo $row['idOrdenes']?>">
                    <input type="submit" value="ELIMINAR" name="eliminar">
                </div>
            </div><br><br>
            <?php if($_POST['eliminar']) {
                    $id_eliminar = intval($_POST['id']);
                    $sql3 = "DELETE FROM lecturas_db.items WHERE idOrdenes = $id_eliminar LIMIT 1";
                    $res1 = mysqli_query($conexion,$sql3);
                    if($res1 > 0) {
                        echo "<script>
                        location.href='index.php';
                        </script>";
                    } else {
                        echo "nada";
                    } 
                } 
                $isbn = $row['libro'];
                $cantidadOrdenes = $row['cantidad'];
                $usuario = $row['usuario'];
                $precio = $row['precio']*$row['cantidad'];
                echo $isbn;
                echo $cantidadOrdenes;
                echo $usuario;
                echo $precio;
                ?>
        </form>
            <?php } ?>
    
asked by Juan enriquez 02.12.2018 в 16:10
source

1 answer

1

The management of arrays in the forms is done by enclosing brackets [] in the name of the element, something like this:

<?php  foreach($articulos as $articulo ) {?>
    <input name="id[]" value="<?=$articulo['id']?>" type="hidden">
    <input name="nombre[]" value="<?=$articulo['nombre']?>">
    <input name="precio[]" value="<?=$articulo['precio']?>">
    <button type="submit" value="<?php echo $articulo['id'] ?>" name="eliminar">Eliminar</button>
<?php } ?>

This way you will get three arrays: $ _POST ['id'], $ _POST ['name'] and $ _POST ['price'] with as many elements as you have repetitions in the html.

Leaving the empty brackets will generate an automatic numerical index, but if you prefer you can indicate a specific index:

PHP

<?php  foreach($articulos as $articulo ) {?>
    <input name="nombre[<?=$articulo['id']?>]" value="<?=$articulo[$contador]['nombre']?>">
    <input name="precio[<?=$articulo['id']?>]" value="<?=$articulo[$contador]['precio']?>">
    <button type="submit" value="<?php echo $articulo['id'] ?>" name="eliminar">Eliminar</button>
<?php } ?>

HTML

    <input name="nombre[1025]" value="monitor">
    <input name="precio[1025]" value="150.25">
    <button type="submit" value="1025" name="eliminar">Eliminar</button>
    <input name="nombre[60]" value="teclado">
    <input name="precio[60]" value="15">
    <button type="submit" value="60" name="eliminar">Eliminar</button>

In this case we will use the id of the element as an index of the data array.

In your case it would be something like this:

<div class="eliminarProd">
    <input type="hidden" name="isbn[]" value="<?php echo $row['libro'] ?>">
    <input type="hidden" name="cantidadOrdenes[]" value="<?php echo $row['cantidad'] ?>">
    <input type="hidden" name="usuario[]" value="<?php echo $row['usuario'] ?>">
    <input type="hidden" name="precio[]" value="<?php echo $row['precio'] ?>">
    <input type="hidden" name="id[]" value="<?php echo $row['idOrdenes'] ?>">
    <button type="submit" value="<?php echo $row['idOrdenes'] ?>" name="eliminar">Eliminar</button>
</div>

and to delete (or edit or whatever):

   <?php if($_POST['eliminar']) {
                $id_eliminar = intval($_POST['eliminar']);
                $sql3 = "DELETE FROM lecturas_db.items WHERE idOrdenes = $id_eliminar LIMIT 1";
                ....
    ?>

If you need further clarification, please notify.

(edit)

Your initial code had some errors that I had to comment, I leave the correction that I think you need:

<form method="POST" class="carrito">
<?php while ($row = mysqli_fetch_array($res)) { ?>
        <div class="Prod">
            <div class="imagenProd">
                <img src="<?php echo $direct . $row['imagen'] ?>">
            </div>
            <div class="tituloProd">
                <center><b><?php echo $row['titulo'] ?></b></center>
            </div><br><br>
            <div class="cantidadProd">
                <center><b><?php echo $row['cantidad'] ?></b> unidad/es</center>
            </div><br><br>
            <div class="subtotalProd">
                <center>Subtotal: <b>$<?php
                        $subtotal = $row['precio'] * $row['cantidad'];
                        echo $subtotal;
                        $total += $subtotal;
                        ?></b></center> 
            </div><br><br>           
            <div class="eliminarProd">
                <input type="hidden" name="isbn[]" value="<?php echo $row['libro'] ?>">
                <input type="hidden" name="cantidadOrdenes[]" value="<?php echo $row['cantidad'] ?>">
                <input type="hidden" name="usuario[]" value="<?php echo $row['usuario'] ?>">
                <input type="hidden" name="precio[]" value="<?php echo $row['precio'] ?>">
                <input type="hidden" name="id[]" value="<?php echo $row['idOrdenes'] ?>">
                <button type="submit" value="<?php echo $row['idOrdenes'] ?>" name="eliminar">Eliminar</button>
            </div>                
        </div><br><br>
<?php } ?>
<button type="submit" name="pocesar">Procesar compra</button>
</form>

IMPORTANT: There is only a <form> , so it must be so that all the products arrive (in the form of an array) and not just the last one. And the while loop is inside the form showing each of the items. Finally, the purchase button is outside the loop (only one will appear) before closing the form.

Notice that I deleted the part that processes the deletion, because you had it inside the loop and it should not be like that, the processing is done only once so it goes out of the loop.

Get used to separating the parts of code that print screens from the parties that process the information.

Thus, the party that would process the form remains with:

<?php
if ($_POST['eliminar']) {
    $id_eliminar = intval($_POST['eliminar']);
    $sql3 = "DELETE FROM lecturas_db.items WHERE idOrdenes = $id_eliminar LIMIT 1";
    // resto del codigo de eliminación....
}


if ($_POST['procesar']) {
    foreach ($_POST['id'] as $indice => $id_producto) {

        $id = $id_producto;
        $cantidadOrdenes = $_POST['cantidadOrdenes'][$indice];
        $precio = $_POST['precio'][$indice];

        // resto del codigo de la compra (para cada articulo)....
    }

    // resto del codigo de la compra 
}

?>

Each of the articles will arrive in an array, which, in this case, we read sequentially. And now you can save one at a time, or build the SQL that saves all at once or what you prefer.

Greetings.

Notes:

1 <?=$variable?> is a short way to put <?php echo $variable ?>

    
answered by 02.12.2018 / 19:26
source