Transform name of fields posted in PHP variables

0

I have a form with dynamic fields. with inputs with names like this:

<input type="hidden" name="nome_prod1" value="Shampoo Hidratante Dazen Elegance">
<input data-theme="b" value="0" name="qtd1" type="text" id="1"/>

<input type="hidden" name="nome_prod2" value="Shampoo Hidratante Dazen Elegance">
<input data-theme="b" value="0" name="qtd2" type="text" id="1"/>

Each one with its value, the problem is the time to show this because I did not want to show so little save in the bank the fields that have quantity 0 .

I used the command:

foreach( $_POST as $nome_campo => $valor)
{ 
   $comando = "$" . $nome_campo . "='" . $valor . "';"; 
   eval($comando); 
}

But he brought all the inputs, I tried to try not to show the ones with qtd = 0 but the problem is in searching for the variable I put a $i counter inside foreach , then the name of the variable qtd I tried to call it like this:

if ($qtd{$i} == 0 ) {}

But it did not work, how do I do that fetch a dynamic variable?

$qtd1
$qtd2
$qtd3
    
asked by anonymous 01.10.2016 / 16:57

1 answer

3

First of all, responding to what was asked, one way would be to use "variable variables":

foreach( $_POST as $nome_campo => $valor) { 
   $$nome_campo = $valor;
}

But this is far from a good idea. Any misuse of your PHP (for example, the client sending arbitrary data) will override application variables.

As well remembered by Pope Charlie, PHP even has something ready that already does this automatically, extract() .

Since the solutions above (either extract or loop ) have their inherent problems, a more elegant solution would be to use this structure:

<input type="hidden" name="nome_prod[]" value="Shampoo Hidratante Dazen Elegance">
<input data-theme="b" value="0" name="qtd[]" type="text" id="1"/>

And in PHP something like this:

$nome  = $_POST['nome_prod'];
$qtd   = $_POST['qtd'];

// aqui é só usar os dados como quiser, já estão indexados desde a captura.
$count = count( $qtd );
for( $i = 0; $i < $count; ++$i ) {
   echo 'Produto: '.$nome[$i].' - Quantidade: '.$qtd[$i]."<br>\n";
}

In a full application, it is necessary to sanitize the data before use, obviously (regardless of the approach used).

As for not using zero values, just something like this in the loop :

if( 0 + $qtd[$i] ) {
    // usa o valor como quiser
}

The code inside the if block will only be executed with values other than 0. The artifice used is to force a cast with 0 + to treat the value as numeric (there are several ways to if you do this, this is one of them, see how to do the casts and conversions in the PHP manual, in the variables part).

    
01.10.2016 / 17:52