开发者

reading two form elements with same name

开发者 https://www.devze.com 2023-02-24 00:29 出处:网络
<form action=\"test.php\" method=\"post\"> Name: <input type=\"text\" name=\"fname\" /> <input type=\"hidden\" name=\"fname\"value=\"test\" />
<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" />
<inpu开发者_如何学Pythont 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号