Thursday, 30 August 2018

HTML form submitted to the PHP script with associative array

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 ?

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];

0 comments:

Post a Comment