how to get post from same name textboxes in php

2020-05-03 12:36发布

I have a form with multiple textboxes which are created dynamically, now all these textboxes are of same name lets say txt, now is there any way that when form processing happens we could read all the text boxes values using $_POST method, which are of so called same name. If possible how?

3条回答
我想做一个坏孩纸
2楼-- · 2020-05-03 12:56

Create your text box with names txt[]

<input type='text' name='txt[]'>

And in PHP read them as

$alTxt= $_POST['txt'];
$N = count($alTxt);
    for($i=0; $i < $N; $i++)
    {
      echo($alTxt[$i]);
    }
查看更多
ら.Afraid
3楼-- · 2020-05-03 13:06

You have to name your textboxes txt[] so PHP creates a numerically indexed array for you:

<?php
// $_POST['txt'][0] will be your first textbox
// $_POST['txt'][1] will be your second textbox
// etc.    

var_dump( $_POST['txt'] );
// or
foreach ( $_POST['txt'] as $key => $value )
{
  echo 'Textbox #'.htmlentities($key).' has this value: ';
  echo htmlentities($value);
}

?>

Otherwise the last textbox' value will overwrite all other values!

You could also create associative arrays:

<input type="text" name="txt[numberOne]" />
<input type="text" name="txt[numberTwo]" />
<!-- etc -->

But then you have to take care of the names yourself instead of letting PHP doing it.

查看更多
干净又极端
4楼-- · 2020-05-03 13:18

If you want name, you could name the input with txt[name1], then you could get it value from $_POST['txt']['name1']. $_POST['txt'] will be an associative array.

查看更多
登录 后发表回答