1

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 ?

0

3 Answers 3

3

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];
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.