Foreach in Post PHP return

Asked

Viewed 1,208 times

0

Opa,

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

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

The problem I have is that when registering only one item, the Insert is normally performed, but when informing more items, only the first set of data is inserted, is the second returns with values 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 you print 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
)

There’s something wrong with my foreach?

The fields of the same name have the same name, following a pattern: name="id_numero[]"

Check that when you print 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

  • I don’t understand why you’re rewriting the $_POST, besides, you put a value, $n, would already bring the value.

  • I am doing maintenance on a system that I do not know, the function of Insert in BD captures the posts of the form, I had to rewrite it to work. Vlw

  • but ideally you pass a new array, in this case...

  • Just do not replace the POST as I was doing this code, I inserted the columns and fields directly in the Dbcreate field, and everything started to work normally. Too bad I’ll have to edit the whole system, poorly designed code :(

  • I can see that.

  • Fix the title there, Forech is wrong, it’s Foreach

Show 1 more comment

2 answers

1


The fields numero, id_operadora, dt_cadastro, status and id_numero are arrays with increasing numeric keys, so you can process them in a foreach thus:

$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, and therefore $_POST['id_usuario'][$key] seems to be wrong.


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

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

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

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

  • Opa, thanks for answering André, I inserted the while inside the foreach, there was the same, the other fields came zeroed. I corrected the id_usuario, vlw same.

  • Gave an echo in the post after inside the while, returned me the same data from the previous echo. I wonder what’s wrong?

  • Solved, vlw André

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);
}

Browser other questions tagged

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