Search only form fields with value other than 0 and put in PHP variable

Asked

Viewed 52 times

2

I have a quote form with 70 products in which the user chooses the amount of products he wants from each one.

All are named with id P1, P2...P70 and are number type inputs.

<form method="post">
<input type="number" value="0" name="p1" id="p1">
<input type="number" value="0" name="p2" id="p2">
...
<input type="number" value="0" name="p70" id="p70">
</form>

I need a PHP function that only inserts items other than 0 (which is the default value) into a variable to mount a table that will be exported to excel.

Here’s what I got:

// Monta o cabeçalho da tabela    
$data = '<table><tbody><tr><td>CABEÇALHO</td></tr>';

// Traz cada linha que o valor é diferente de 0
if($_POST['form']['p1'] != '0'){
    $data .= '<tr><td>'.$_POST["form"]["p1"].'</td></tr>';
}
if($_POST['form']['p2'] != '0'){
    $data .= '<tr><td>'.$_POST["form"]["p2"].'</td></tr>';
}

// Coloca o rodapé e fecha a tabela
$data .= '<tr><td>RODAPÉ</td></tr></tbody></table>';

The problem with what I did is that I would have to have 70 ifs, I believe there should be a simpler way, but I don’t know which.

2 answers

3

<?php 
cabeçalho...

foreach($_POST['form'] as $value){
   $table .= ($value) ? '<tr><td>'.$value.'</td></tr>'; : '';
}

footer...

If there are changes in the amount of items, the code still has to work.

2


Loop 1 to 70 by creating the lines where the value of $_POST is different from 0:

    <?php
$data = '<table><tbody><tr><td>CABEÇALHO</td></tr>';

for($x=1;$x<=70;$x++){
  if($_POST['form']['p'.$x] != '0'){
   $data .= '<tr><td>'.$_POST['form']['p'.$x].'</td></tr>';
  }
}

$data .= '<tr><td>RODAPÉ</td></tr></tbody</table>';
    ?>

Browser other questions tagged

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