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">
– Marcos Vinicius
Got it, but you know how I get this value in php?
– Lucas
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.
– Marcos Vinicius
Got it, thanks for the reply
– Lucas