Home > Blockchain >  Generate multiple Form Inputs php
Generate multiple Form Inputs php

Time:11-24

How do i get the values when submitted I am generating the input via a loop based on the users selection but don't know how to retrieve the input values via post method

here is a sample of what i have

// string is based on database values it can be anything which i can't tell
Example code

$string = 'math,english,biology';

$exp = explode(',', $string);
foreach($exp as $value){
    print '<input type="text" name="'.$value.'[]" value=""  />
}

CodePudding user response:

You don't have to use name array (name="blabla[]")

$string = 'math,english,biology';

$exp = explode(',', $string);


if ($_POST) {
    foreach ($exp as $name) {
        if (isset($_POST[$name])) {
            echo 'input ' . $name . ' is ' . $_POST[$name] . '<br>';
        }
    }
    exit();
}


echo '<form method="post">';
foreach($exp as $value){
    print '<input type="text" name="'.$value.'" value=""  />';
}
echo '<button type="submit">Submit</button></form>';

Enter a, b, c to each input and submit. Here is the result:

input math is a
input english is b
input biology is c

CodePudding user response:

Put the value in value="", name the field and make it an array [].

$string = 'math,english,biology';

$exp = explode(',', $string);
foreach ($exp as $value) {
    echo '<input type="text" name="fieldName[]" value="<?= htmlentities($value) ?>"  />
}

Then it will be accessible in *$_POST['fieldName'] as an array.

*presuming you are using method="POST" on the form

If math,english,biology are form keys, then do:

$string = 'math,english,biology';

$exp = explode(',', $string);
foreach ($exp as $key) {
    echo '<input type="text" name="fieldName[<?= htmlentities($key) ?>]" value=""/>
}

or

$string = 'math,english,biology';

$exp = explode(',', $string);
foreach ($exp as $key) {
    echo '<input type="text" name="<?= htmlentities($key) ?>" value=""/>
}
  • Related