Reputation: 511
I'm making an HTML form. I want the results to appear in the PHP script on another page.
Here is my form :
echo '<form name="form1" action="page2.php" method="post">';
echo '<SELECT name="choice">';
foreach ($array as $key => $value)
echo '<OPTION VALUE="'.$value.'" name="'.$value.'">'.$key.'</OPTION>';
Now, on my page2.php I want to retrieve both $key AND $value using the "post" method, I tried these 3 solutions one by one and it failed :
echo $_POST["choice"]; //nothing
echo $_POST[$key]; //nothing
echo $_POST[$value]; //nothing
What is the problem ?
Upvotes: 1
Views: 1024
Reputation: 611
You can have a delimiter in the value of your options like this:
echo '<form name="form1" action="page2.php" method="post">';
echo '<SELECT name="choice">';
foreach ($array as $key => $value)
echo '<OPTION VALUE="'.$key.'|'.$value.'" >'.$value.'</OPTION>';
and then, on post, retrieve it this way:
$expldedArray = explode("|", $_POST["choice"]);
$key = $expldedArray[0];
$value = $expldedArray[1];
Upvotes: 3
Reputation: 2673
foreach($_POST as $key => $value) {
echo ucfirst($key); echo " = ";
if(is_array($value))
echo implode(",", $value);
else
echo $value;
echo '<br />';
}
Where ucfirst()
capitalizes first letter of string.
implode()
will glue array elements with given string
Upvotes: 2
Reputation: 5202
You dont need to give a name to the option in select field. Just give a name to the select tag like below:
echo '<form name="form1" action="page2.php" method="post">';
echo '<SELECT name="choice">';
foreach ($array as $key => $value)
echo '<OPTION VALUE="'.$value.'">'.$key.'</OPTION>';
and then in your php code after selecting a value and submitting the form:
echo $_POST['choice']
will give you the selected value.
Upvotes: 3