0

I have a form that may submit 1 line item or 200 to quote. using FPDF to create results and everything is working perfectly, but I was looking for a way to automate picking up post values. So far I have been doing them manually, which is very difficult to make code changes:

//conditional statement to verify values exist, otherwise we write a blank line
$item=$_POST['item3'];
$uprice=$_POST['uprice3'];
$udprice=$_POST['udprice3'];
$quan=$_POST['quan3'];
//add values to report
//repeat for next result
$item=$_POST['item4'];
$uprice=$_POST['uprice4'];
$udprice=$_POST['udprice4'];
$quan=$_POST['quan4'];

I was wondering if there is a way to add a variable inside the post value, like $_POST[$nextitem]?

NDM
  • 6,731
  • 3
  • 39
  • 52

2 Answers2

3

You can loop until the next number is not available anymore:

<?php
$i = 1;
while (isset($_POST['item' . $i])) {
    $item = $_POST['item' . $i];
    $uprice = $_POST['uprice' . $i];
    $udprice = $_POST['udprice' . $i];
    $quan = $_POST['quan' . $i];

    // do your stuff

    $i++;
}

concatenating a string 'var' with int 1 will result in a string 'var1' in PHP.

NDM
  • 6,731
  • 3
  • 39
  • 52
1

I would just grab the entire array with $array = $_POST and then use foreach() loops to manipulate it later.

Alternatively, it sounds like you have an arbitrary number of things on your form. Do it like this:

<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />


<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />


<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />


<input type="text" name="item[]" />
<input type="text" name="quan[]" />
<input type="text" name="udprice[]" />

You can see more about this in this very helpful answer: HERE

When you submit this arbitrary number of fields, you will end up with a nice multi-dimensional array. Iterate over it like this:

$i =  count($_POST['item']);
$payload = array();
while ($i <= count($_POST['item']) {
    $payload[] = array(
       'item' => $_POST['item'][$i],
       'udprice' => $_POST['item'][$i],
       'quan' => $_POST['quan'][$i]
    );
    $i++;

}

Now $payload is a fancy array that can be inserted into databases and such.

Community
  • 1
  • 1
David
  • 3,831
  • 2
  • 28
  • 38