How to save multiple inputs with the same "name"?

Asked

Viewed 3,746 times

8

I need to save several input that contains the same "name", but the problem is that it only saves one single result for several. Example:

<form method="post" action="guardar.php">
    <input type="hidden" name="produto" value="teste1">
    <input type="hidden" name="produto" value="teste2">
    <input type="hidden" name="produto" value="teste3">
    <input type="hidden" name="produto" value="teste4">
    <input type="hidden" name="produto" value="teste5">
    <input type="submit" value="enviar">
    </form>

PHP:

$produtos = $_POST["produto"];
    mysql_query("INSERT INTO produtos (produtos) VALUES ("$produtos"") or die("Erro  query.<br>Mensagem do servidor: ".mysql_error());

But in the bank comes only:

teste1

How I would save all input values if they have the same name?

Updating:

Problem solved by adding [] as name of input, turning it into a array and then treat them with foreach.

  • 1

    'Cause you don’t change the name, in this particular case I’m not seeing any reason to use the same name.

  • the problem is that these input are automatically generated with each user click on a value on the site. if it selects 3 products? would have to be a input products for each, wanted to try another way besides generating a input with a name different for each item.

  • 6

    If you name it produtos[] to their inputs, I believe they will be sent to PHP as an array.

1 answer

13


Hello, as said in the comments, just turn them into an array:

HTML

<form method="post" action="guardar.php">
    <input type="hidden" name="produto[]" value="teste1">
    <input type="hidden" name="produto[]" value="teste2">
    <input type="hidden" name="produto[]" value="teste3">
    <input type="hidden" name="produto[]" value="teste4">
    <input type="hidden" name="produto[]" value="teste5">
    <input type="submit" value="enviar">
</form>

In PHP you place the Inserts inside a loop that passes through the array fields:

PHP

foreach($_POST["produto"] as $produto) {
    mysql_query("INSERT INTO produtos (produtos) VALUES (".$produto.")") or die("Erro  query.<br>Mensagem do servidor: ".mysql_error());
}

I hope I’ve helped

  • 3

    +1 I recommend checking whether there is an entry produto and whether it is a matrix before charming the foreach() or we will have some mistakes! Ex.: isset($_POST["produto"]) && is_array($_POST["produto"]).

  • Very good, it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.