How to send information from a dynamic form?

2

I have to make a form where there will be this table, but instead of being static is going to be dynamic, the person can introduce 1 familiar, 2, 3, 4, 10, whatever she wants. For this I am using JQUERY , and whenever the person clicks on an add button adds a new row to the table, this part I know how to do. My question is as follows, how do I then send the whole information to the database, told me that I would have to store in an array , but I array's in PHP I'm not very good.

EXAMPLEMY

parthtml

<form method="post" id="formulario" action="dados.php">  
        
                <div id="telefone">  
            <p><label>Nome</label><input type="text" class="fone" name="agregado[]" size="15" /><span class="adicionar">Adicionar registo</span></p>  
            <p><label>telefone</label><input type="text" class="fone" name="agregado[]" size="15" /></p>  
       </div>  
            <p><input type="submit" value="Enviar" id="btEnviar" name="btEnviar" />  
     </form> 

PART DATA.PHP

$ligacao = mysqli_connect("localhost", "root", "", "teste");
                        if (mysqli_connect_errno()) {
                            echo "Erro na liga??o MySQL: " . mysqli_connect_error();
                        }

$result = count($_POST["agregado"]);
$agregado=$_POST["agregado"];
var_dump($agregado);

for($i=0; $i<$result; $i++){
    $sql="insert into teste (nome) values ('$agregado[i]', '$agregado[i]')";//DUVIDA
    echo $sql;
}

As soon as I get to this part I do even the var_dump($agregado) where the output is something like this

array(2) { [0]=> string(4) "pessoa" [1]=> string(3) "123" } 

This is the output for the case of entering 1 person, if you enter 2 the output will be:

array(4) { [0]=> string(4) "pessoa" [1]=> string(3) "123" [2]=> string(5) "pessoa_2" [3]=> string(3) "234" }

and so on

How do I insert each position of the array into its proper place?

I make it to go through all the positions of the array but then I can not get it to enter the correct position.

    
asked by anonymous 30.04.2015 / 18:09

1 answer

1

Well, if you know how to do the jQuery part is a start. From jQuery you can send the values to PHP through POST in several ways, JSON, array, csv, or other.

By imagining a csv, to make the example easier, imagine that we have a text field, where the delimiter of the various lines is a ";" and that the delimiter of the fields is a ","

// variavel POSTed por jQuery
$csv = "nome1,parentesco1,idade1,contacto1;nome2,parentesco2,idade2,contacto2"

If the form field is called 'items', you should access it using $ _POST ['items']. Then:

$items = explode(";", $csv);

foreach ($items as $item) {
$colunas = explode(",", $item);
// Inserir aqui na base de dados, usando $coluna[0], $coluna[1], ..., $coluna[N]
}

Warning that this code was made from my head, it is not tested.

    
30.04.2015 / 18:34