Home > Mobile >  Post Method only posting last value fetched from database
Post Method only posting last value fetched from database

Time:05-24

I am displaying list of items(multiple entries) from database on one page. I am trying to post all those values fetched from the database to another php file to add item to cart.

But when I press 'add to cart' button for any item in the list, it is only sending last item through POST. I know it is because of while loop, but I don't know correct way to implement it?


<form action="php/addToCart.php" method= "POST">
    <?php
        while($product=mysqli_fetch_assoc($featured)):
    ?>
    <div >
        <h4><?= $product['title'] ?></h4>
        <image src="php/marketplace_images/<?= $product['image'];?>" alt="<?= $product['title'];?>" height="300" width="300"/>
        <p > Price $ <?= $product['price'];?></p>
        <p > Description: <?= $product['description'];?></p>
        <p > Brand Name: <?= $product['brandname'];?></p>

        <input name="title" type="hidden" value="<?= $product['title'] ?>" />
        <input name="price" type="hidden" value="<?= $product['price'] ?>" />
        <input name="brandname" type="hidden" value="<?= $product['brandname'] ?>" />
        <input name="image" type="hidden" value="<?= $product['image'] ?>" />
        <input name="featured" type="hidden" value="<?= $product['featured'] ?>" />
        <button type="submit"  data-toggle="modal" name="add">Add To Cart</button>      
                              
    </div>
    <?php endwhile;
 ?>

CodePudding user response:

You're ending up with a single form with n (as many as items) fields with the same name, that are no longer separate. E.g. you'll have n fields named "title", n fields named "price" etc.

You'd never know which title belongs to which price.

Plus, the code you show only shows the rendering of the form, not what you're doing with it on submission (but that wouldn't make it better, as you can't distinguish between all the different inputs). If that code expects one title, it might take the last, or a random one.

So, if you want to send just a single item: Move your <form> and </form> into the while loop, so that you end up with a number of forms that can be individually submitted. In general I'd recommend against posting all of the data and just limit yourself to an id of an item, but that's beyond the scope of this question (but imagine what happens when I manipulate the price to 0 before submitting the item to the cart)

  • Related