user4252099
user4252099

Reputation:

Input hidden doesn't work properly

I'm developing a simple PHP page, this is a small part of my code that doesn't work properly.

I want to use DB and print some products and for each product, I want to show a "buy" button.

If I press this button, a hidden input must be set with the product id(which later has to be sent to another page).

But, if I use var_dump to control(if my data was correct), I can see that the ID is wrong (I see that its always shown in the last)

  <form id="products_list" method="post" action="step2.php">
  <table>
   <tr>
    <td align="center">Immagine</td>
    <td align="center">Nome prodotto</td>
    <td align="center">Descrizione prodotto</td>
    <td align="center">Prezzo unitario</td>
    <td align="center">Taglie disponibili</td>
    <td align="center">Colori disponibili</td>
    <td align="center">Nickname disponibili</td>
   </tr>

  <?php
   $product = mysqli_query($mysqli, "SELECT * FROM products");
   while ($row = mysqli_fetch_array($product)) {
    $id = $row[id_products];
    print("
    <tr>
     <td align=\"center\">".$row[img_products]."</td> 
     <td align=\"center\">".$row[name_products]."</td>
     <td align=\"center\">".$row[description_products]."</td>
     <td align=\"center\">".$row[price_products]."</td>
     <td align=\"center\">".$row[size_products]."</td>
     <td align=\"center\">".$row[color_products]."</td>
     <td align=\"center\">".$row[nick_products]."</td>
     <input type=\"hidden\" name=\"id_products\" value=\"".$id."\"/>

     <td><input type=\"submit\" name=\"buy\" value=\"Acquista\"/></td>
    </tr>");
   }
  ?>
   </table> 
   </form>

Upvotes: 1

Views: 264

Answers (1)

Raaamy
Raaamy

Reputation: 91

You should open and close your form within the while-loop.

EDIT

A little bit more explanation why you should open and close from within the while loop: If the while-loop is inside the form tags, that means the hidden field is outputted multiple times within the same form. Since they are all named the same, you're only retrieving one value after the submit (the value of the last hidden input). If you open and close the form within the while-loop, each hidden input and button are in their own form. Which means, when that form gets submitted, you're only retrieving the value of that specific hidden field. :-)

Upvotes: 1

Related Questions