Shasapo
Shasapo

Reputation: 193

How to get the input value from multiple value when button pressed php

i want to make a cart and my product is pizza. so i'm listing all the menu to the table, and add a button to submit menu to cart.

here's my index.php

<?php
require("connect.php");
$result = mysqli_query($con,'select * from menu');
?>


<form action="cart.php" method="get">
    <table  border="1" style="width:100%">
        <tr>
            <th>Pizza Name</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Buy</th>
        </tr>
        <?php while($product = mysqli_fetch_object($result)){ ?>
            <tr>
                <td><?php echo $product->nama_menu; ?></td>
                <td><?php echo $product->harga_menu; ?></td>
                <td><input type="number" name="quantity" min="1" max="20"></td>
                <td><button type="submit" name="id" value="<?php echo $product->id_menu; ?>">Add To Cart</button></td>
            </tr>
        <?php } ?>
    </table>
</form>     

But when i pressed the button "Add To Cart", it sends all the quantity from the menu listing and can't be read in my cart.php

can anyone help me how to get the right quantity value when i pressed the button add to cart.

Upvotes: 0

Views: 65

Answers (2)

sandeepsure
sandeepsure

Reputation: 1115

Make separate form for each of the item. Try below code.

<?php
require("connect.php");
$result = mysqli_query($con,'select * from menu');
?>



    <table  border="1" style="width:100%">
        <tr>
            <th>Pizza Name</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Buy</th>
        </tr>
        <?php while($product = mysqli_fetch_object($result)){ ?>
            <form action="cart.php" method="get">
            <tr>
                <td><?php echo $product->nama_menu; ?></td>
                <td><?php echo $product->harga_menu; ?></td>
                <td><input type="number" name="quantity" min="1" max="20"></td>
                <td><button type="submit" name="id" value="<?php echo $product->id_menu; ?>">Add To Cart</button></td>
            </tr>
            </form>
        <?php } ?>
    </table>

Upvotes: 1

RJParikh
RJParikh

Reputation: 4166

Try to use array in name then submit it will give you seperate quantity.

<td><input type="number" name="quantity[<?php echo $product->nama_menu; ?>]" min="1" max="20">

Output: quantity['pizza1'] = 10 quantity['pizza2'] = 20 ....

Another Option is use dynamic name for number.

<td><input type="number" name="quantity_<?php echo $product->nama_menu; ?>" min="1" max="20">

Output: quantity_pizza1 = 10 quantity_pizza2 = 20 ....

Upvotes: 0

Related Questions