How to receive multiple fields in php and insert in table(mysql), not knowing the amount

Asked

Viewed 364 times

1

First question here, so if you need anything else, please let me know. I have a simple html screen that has a basic table and in this table there are inputs where put the values description and value (a cost control system), I created in javascript a command that when clicking the "Add" button, adds 2 other fields equal to those mentioned. I want to receive this data by php,but I don’t know how because I don’t know how many fields a person will want to fill in and how to receive and treat them. I know they will come as arrays and I have to transform to string,.

Note: has the save button that is already configured, but does not have the values that will enter in the bank.

Html code

    <table id="tabela">
                <th>Descrição</th>
                <th>Valor</th>

      <tr>
        <td><input type="text" name="r1[]" id="desc" placeholder="Descrição"></td>
        <td><input type="text" name="r2[]" id="valor" placeholder="Valor"></td>
      </tr>
        <a href="#" id="add">adicionar campo</a>
        <input id="enviar" type="submit" value="salvar">

         <script src="main.js"></script>

PHP code

<?php

require_once "conexao.php";

$desc = $_POST['r1'];
$valor = $_POST['r2'];

$result = count($desc);

for ($i = 0; $i < ($result) ; $i++) {

      $dataString .= " ('$desc[$i]', '$valor[$i]'),";
}

// retira a ultima virgula

$values = substr($dataString, 0, -1);

//a query para inserir os dados no banco 

$sql = ("INSERT INTO tbtable (r1,r2) VALUES $values");


mysqli_query($conexao,$sql);

mysqli_close($conexao);

Javascript code

const btn = document.getElementById('add').addEventListener('click', function(){
    var table = document.getElementById('tabela')
    var row = table.insertRow(2)

row.insertCell(0).innerHTML = `<input type="text" name="r1[]" placeholder="Descrição">`
row.insertCell(1).innerHTML = `<input type="text" name="r2[]" placeholder="Valor">`
})

In the table of the bank has 3 columns (id,R1,R2), in the case would result 1 and result 2.

  • the attribute name must be R1 or R2 but since there must be more instances then you must insert [] thus: <input type="text" name="R1[]" placeholder="Description">

  • Got it, but you know how I get this value in php?

  • example: $R1 = $_POST['R1']; but as it will arrive as an array you will have to iterate over that $R1 array using a foreach for example.

  • Got it, thanks for the reply

1 answer

1


You: "I know that they will come as arrays and that I have to transform to string, but I could not perform this, let alone put in the table in the database."

Marcos Vinicius - the attribute name must be R1 or R2 but since there must be more instances then you must insert [] so:

<input type="text" name="r1[]" id="desc" placeholder="Descrição">

I

A single INSERT statement ... VALUES can add multiple records to a table if you provide multiple lists of values. To do this, provide a list of values in parentheses for each record and separate the lists with commas.

INSERT INTO tbtable (r1,r2) VALUES ('pera', '12'), ('uva', '13'), ('maça', '14')

//recuperando valores passados pelo formulario
$codProduto = $_POST['r1'];
$qtdProduto = $_POST['r2'];

// usando um foreach para construir os values do insert
$result = count($codProduto);

for ($i = 0; $i < ($result) ; $i++) {

      $dataString .= " ('$codProduto[$i]', '$qtdProduto[$i]'),";

}

// retira a ultima virgula
$values=substr($dataString, 0, -1);

//a query para inserir os dados no banco 
$sql = ("INSERT INTO tbtable (r1,r2) VALUES $values");
  • It worked in parts, it registers in the database yes, but if I add more than one field with javascript and put the values, it only inserts the value that is in the fields filled by html,ie, if I add 2 more fields by javascript it does not pass these values to the database.

  • @Lucas, in javascript you renamed input numbers to name="R1[]" and name="R2[]"

  • Yes, I did, but it didn’t work that way

  • Now I managed to realize, but returns an error, Notice: Undefined variable: dataString in C: xampp htdocs testetable index.php on line 12, know why?

  • @Lucas, what was missing to work?

  • has how to post the full codes?

  • I pulled the stitch after $dataString.= " ('$codProdut[$i]', '$qtdProdut[$i]') ,"because I didn’t understand its functionality, and because it was returning the error,but when I left it worked, even with the error

  • I’ll edit the question with the code as it is now

  • your form does not have <form method="POST" action="page_destination">

  • Initialize the variable at the beginning of PHP $dataString = "";

  • It worked perfectly, thank you very much.

Show 6 more comments

Browser other questions tagged

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