How to handle dynamic input fields in post method using Php

oceanwap

New Member
Messages
24
Reaction score
0
Points
0
I have created a script to allow user to input text inside a form using post method having user defined no of fields.
Here is the code:-
PHP:
if(isset($_get['url_no']))
{
<form name="myform" action="'.$_SERVER['PHP_SELF'].'" method="post">
$counter = 1;
$url_no = 1;
while ($url_no <= $_GET['url_no'])
{
echo 'title:<input type = "text" name="title'.$counter.'" ><br/>
link:<input type = "text" name="url'.$counter.'" ><br/>
';
$url_no++;
$counter++;
}
<input type="submit" name="submit">
</form>
}
Now how I can process this form and generate set of anchor tags with user supplied title and url.
 

masshuu

Head of the Geese
Community Support
Enemy of the State
Messages
2,293
Reaction score
50
Points
48
i would say, make a hidden input, give it $_GET['url_no']
then when posted, check the hidden feild, and just use something like
PHP:
$Count = $_POST['hiddenCount'];
$Data = "Your Links: <br />";
for($i = 0; $i < $Count; $i++)
{
   $Data .= '<a href="' . $_POST['url'.$i] . '>' .  $_POST['title'.$i] . '</a><br />';
}

alternatively, you could do:
PHP:
$i = 0;
$Data = "Your Links: <br />";
while(isset( $_POST['url'.$i]))
{
   $Data .= '<a href="' . $_POST['url'.$i] . '>' .  $_POST['title'.$i] . '</a><br />';
   $i++;
}
which doesn't need to have a hidden value with the count.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Use array syntax in the form input names to get the input as arrays:
PHP:
<?php
for ($i=0; $i < $_GET['url_no']; ++$i) {
  ?><label for="title_<?php echo $i ?>">Title:</label><input name="title[]" id="title_<?php echo $i ?>" />
  <label for="url_<?php echo $i ?>">Link:</label><input name="url[]" id="url_<?php echo $i ?>" />
  <?php
}
You can use count or foreach in your loop over input elements.
PHP:
for ($i=0; $i < count($_POST['title']); ++$i) {
   ... $_POST['title'][$i] ...
   ... $_POST['url'][$i] ...
}
 
Last edited:
Top