Foreach in Post PHP return

0

Opa,

I have a form in which I send via post the data of the form and capture by a forech.

In the form I have a button in which I create new inputs by append jquery, inputs with same name.

The problem I have is that when registering only one item, the Insert is performed normally, but when informing more items, only the first set of data is inserted, the second one is returned with values of 0.

The code to retrieve the values are:

foreach( $_POST['numero'] as $key => $n ) {


    $data_cadastro = explode('/', $_POST['dt_cadastro'][$key]);
    $data_cadastro = $data_cadastro[2].'-'.$data_cadastro[1].'-'.$data_cadastro[0];


    $telefone_numero = str_replace("(", "", $_POST['numero'][$key]);
    $telefone_numero = str_replace(")", "", $telefone_numero);
    $telefone_numero = str_replace("-", "", $telefone_numero);
    $telefone_numero = str_replace(" ", "", $telefone_numero);


    $_POST['id_usuario']         = $_POST['id_usuario'][$key];
    $_POST['numero']             = $telefone_numero;
    $_POST['id_operadora']  = $_POST['id_operadora'][$key];
    $_POST['dt_cadastro']        = $data_cadastro;
    $_POST['status']             = $_POST['status'][$key];
    $_POST['id_numero']          = $_POST['id_numero'][$key];

    $result     = DBCreate($tbl, $_POST, TRUE, TRUE);

}

When giving a print in the post, I get this:

Array
(
    [id_usuario] => 3
    [numero] => 82999999999
    [id_operadora] => 1
    [dt_cadastro] => 2016-04-14
    [status] => 1
    [id_numero] => 23232323
)



Array
(
    [id_usuario] => 
    [numero] => 2
    [id_operadora] => 
    [dt_cadastro] => --0
    [status] => 
    [id_numero] => 3
)

Is there something wrong with my foreach?

Fields of the same name have the same name, following a pattern: name="id_number []"

Check that when giving a print in the post before foreach I get:

Array
(
    [id_usuario] => 31
    [numero] => Array
        (
            [0] => (82) 99999-9999
            [1] => (82) 8888-8888
        )

    [id_operadora] => Array
        (
            [0] => 1
            [1] => 5
        )

    [dt_cadastro] => Array
        (
            [0] => 14/04/2016
            [1] => 14/04/2016
        )

    [status] => Array
        (
            [0] => 1
            [1] => 1
        )

    [id_numero] => Array
        (
            [0] => 23232323
            [1] => 9830048884
        )

)

That is, the values are correct before the foreach

    
asked by anonymous 14.04.2016 / 19:26

2 answers

1

The fields numero , id_operadora , dt_cadastro , status , and id_numero are arrays with ascending numeric keys, so you can process them in foreach like this:

$key = 0;
while ( isset( $_POST['numero'][$key] ) )
{
    ...
    $key++;
}

The other accesses are the way you are already working, with $_POST['numero'][$key] .

But notice that id_usuario is not an array, so $_POST['id_usuario'][$key] seems to be wrong.

From the second part, notice that you are deleting your own data. For example the line:

$_POST['id_usuario'] = $_POST['id_usuario'][$key];

Transforms the $_POST['id_usuario'] of an array to a single value, so it only works once.

What you have to do there is to create a new array, only with the data that DbCreate needs, and leave $_POST untouched.

    
14.04.2016 / 19:51
0
/*
O id_usuario é uma string. Pegue-o dessa forma direta:
*/
if (isset($_POST['id_usuario'])) {
    $data['usuario']['id'] = $_POST['id_usuario'];

    /*
    Presupõe-se que o array depende da existência do id do usuário, por isso colocamos aqui dentro da condicional do id_usuario
    */
    if (isset($_POST['numero'])) {

        /* 
        Aqui iteramos o array "numero", o qual possui índices iguais aos outros arrays. 
        Isso tem alto risco de falhas, por isso é recomendado criar condicionais mais consistentes.
        Exemplo abaixo:
        */
        foreach ($_POST['numero'] as $k => $v) {
            $data[$k]['id_operadora'] = (isset($_POST['id_operadora'][$k])? $_POST['id_operadora'][$k] : null);
            $data[$k]['dt_cadastro'] = (isset($_POST['dt_cadastro'][$k])? $_POST['dt_cadastro'][$k] : null);
            $data[$k]['status'] = (isset($_POST['status'][$k])? $_POST['status'][$k] : null);
            $data[$k]['id_numero'] = (isset($_POST['id_numero'][$k])? $_POST['id_numero'][$k] : null);
        }

    }

/*
    Teste. Imprime o que foi extraído do $_POST.
    Daqui para frente deve ainda fazer mais verificações, validar os dados, etc.
    */
    print_r($data);
}
    
14.04.2016 / 21:10