简体   繁体   中英

reading two form elements with same name

<form action="test.php" method="post">
Name: <input type="text" name="fname" />
<input type="hidden" name="fname"  value="test" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

How can I read the values of both the fields named fname ?

On my action file(test.php) under $_POST , I am getting only hidden field value.

Is there any PHP setting through which I can read both values?

I believe you want to name the fields as:

Name: <input type="text" name="fname[]" />
<input type="hidden" name="fname[]" value="test" />

to make PHP understand them as an Array.

In case someone wants to do this and doesn't want to change the name of the form elements, or can't, there is still one way it can be done - you can parse the $_SERVER['QUERY_STRING'] or http_get_request_body() value directly.

It would be something like

$vals=explode('&',http_get_request_body());
$mypost=Array();
foreach ($vals as $val) {
  list($key,$v)=explode('=',$val,2);
  $v=urldecode($v); 
  $key=urldecode($key);
  if ($mypost[$key]) $mypost[$key][]=$v;
  else $mypost[$key]=Array($v);
}

This way $mypost ends up containing everything posted as an array of things that had that name (if there was just one thing with a given name, it will be an array with only one element, accessed with $mypost['element_name'][0] ).

For doing the same with query strings, replace http_get_request_body() with $_SERVER['QUERY_STRING']

If you want to pass two form inputs with the same name, you need to make them an array. For example:

<input type="text" name="fname[]" />
<input type="hidden" name="fname[]" value="test" />

You can then access it using the following:

$_POST['fname'][0]
$_POST['fname'][1]

You might want to rethink whether you really need to use the same name though.

Solutions are

1) Try using different name for textbox and hidden value 2) Use an array as mentioned above for field name 3) Its not possible as the values will be overwritten if the names are same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM