I needed to make a dynamic form for online orders. I needed to be able to dynamically create a form with the right amount of required fields for the order. I looked all over for tutorials or examples of code on how to do this, but the only thing I was able to find were simple array tutorials or how to pass data from multiple select boxes etc.
I'm still pretty new to writting my own code and I've been learning through books and online tutorials. This is what I came up with, and it works. I guess it's pretty basic, but hey... I made it so I'm kinda proud of it. 🙂 I'm hoping someone can take a look at it and let me know how I did, and give any pointers as to how to do it better. I'm sure there's easier/better ways of doing things then what I've used, that's why I'm posting it here.
This is just the basic script, I'll be adding validation and strip slashes next, I just wanted to get it working first.
<?php
//checks to see if user has entered a number of rows needed, default is one.
if (isset($_POST['go'])) {
$items = $_POST['items']; //getting post data from first page.
$formrows = 0; //setting formrows variable
echo "<form method='POST' action='";
echo "{$_SERVER['PHP_SELF']}";
echo "'>";
echo "<input type='hidden' name='items' value='$items'>";
echo "<table>
<tr><td>Item No.</td><td>QTY</td><td>Part No.</td><td>Description</td></tr>";
for ($i = 1; $i <= $_POST['items']; $i++) {
// if form rows is less then or equal to items, print one table row and incriment
// $formrows by one until $formrows equeals @items.
echo "<tr><td>$i</td>
<td><input type='text' name='qty[$formrows]' value='' maxlength='3'></td>
<td><input type='text' name='partnum[$formrows]' value='' maxlength='15'></td>
<td><input type='text' name='desc[$formrows]' maxlength='60'>
</td></tr>";
$formrows++;
}
echo "<tr><td colspan='4'><input type='submit' name='submit' value='Submit'></td></tr></table></form>";
}
//checking to see if the submit button has been pressed on page 2.
else if (isset($_POST['submit']) && is_array($_POST['qty']) && is_array($_POST['partnum']) && is_array($_POST['desc'])) {
$qty = $_POST['qty'];
$partnum = $_POST['partnum'];
$desc = $_POST['desc'];
$arraycount = 0;
echo "<table>
<tr><td>Item No.</td><td>QTY</td><td>Part No.</td><td>Description</td></tr>";
for ($lines = 1; ($lines <= $_POST['items']); $lines++) {
echo "<tr><td>$lines</td><td>$qty[$arraycount]</td>";
echo "<td>$partnum[$arraycount]</td><td>$desc[$arraycount]</td></tr>";
$arraycount++;
}
echo "</table>";
}
//Nothing was submitted, show the row selection page.
else {
?>
<form method="POST" action="<?php echo "$_SERVER[PHP_SELF]";?>">
How many items are you ordering? <input type="text" name="items" maxlength="3">
<input type="submit" name="go" value="Go!">
</form>
<?php
}
?>