Insert foreach value into a variable

Asked

Viewed 1,219 times

-2

I am trying unsuccessfully to create a variable with the foreach variables for database insertion, the values are checkbox marked, I am trying this way:

        // buscando os produtos             
        foreach ($_REQUEST['produto'] as $value) {

            $rel0[0] = $value[0];
            $rel1[1] = $value[1];
            $rel2[2] = $value[2];   
            $rel3[3] = $value[3];
            $rel4[4] = $value[4];
            $rel5[5] = $value[5];
            $rel6[6] = $value[6];
            $rel7[7] = $value[7];
            $rel8[8] = $value[8];
            $rel9[9] = $value[9];   

        }

To insert in the bank I’m doing this way:

        // inserindo os produtos no banco de dados
        mysql_select_db($database_conexao, $conexao);       
        $sql = "INSERT INTO relacionamento ( id_produto, id_departamento, rel0, rel1, rel2, rel3, rel4, rel5, rel6, rel7, rel8, rel9 ) values ( '$produto', '$id_departamento', '$rel0[0]', '$rel1[1]', '$rel2[2]', '$rel3[3]', '$rel4[4]', '$rel5[5]', '$rel6[6]', '$rel7[7]', '$rel8[8]', '$rel9[9]' )";
        $queryExec = mysql_query($sql, $conexao) or die("Erro ao inserir relacionamento no banco de dados.");   

Checkboxes are like this:

       <td><input type="checkbox" name="produto[]" id="produto[]" value="<?php echo $row_produtos['id_produto']; ?>" />
          <?php echo $row_produtos['id_produto']; ?></td>
       </tr>
  • What about the checkbox? Show it to us!

1 answer

6


Friend, you are creating 10 arrays without need. Put all with the same variable name, changing only the index. Another thing, the foreach just to go through the array, you should not put all values this way.

foreach ($_REQUEST['produto'] as $value) {
    $rel[] = $value;
}

Remember to also change in your query. The variables $rel0[0], $rel1[1]... should be $rel[0], $rel[1]...

  • 1

    I had also thought about it. That’s why I asked to show how was the checkbox, rsrsrs

  • Fantastic, thanks @Oeslei and Wallace Maxters, was of great help.

Browser other questions tagged

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