如何从PHP变量中的HTML选择中保存所选项?

问题描述:

I have an HTML select where the drop down list is created from a SQL query.

I'm wondering how I can then save the item that the user selects into a PHP variable that I can pass on to other PHP pages.

Thanks.

<tr>
  <td>DRM Staff List</td><span class="required">*</span>:<br />
    <td>
      <select name="unit">
          <?php 
              $conn = oci_connect("username", "password", "url");
              $sql = 'select distinct "DRM Primary" from GIS_DATA_LOAD where "DRM Primary" is not null order by "DRM Primary" asc' ;
              $stid = oci_parse($conn, $sql);
              $success = oci_execute($stid);
              echo $success;
              while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
              {
                  echo "<option value=\"unit1\">" . $row['DRM Primary'] . "</option>";
              }
          ?>
      </select>
    </td>
</tr>

Add you code inside the form tag as below and make a form submit action ($_POST or $_GET) using javascipt as onselect. Since the code is on client side so you have to for sure submit it to the server to save the selected option in a php variable.

    <tr>
    <td>DRM Staff List</td><span class="required">*</span>:<br />
    <td>
      <form action="" method="POST" name="myform">
      <select name="unit" onchange="this.form.submit()>
          <?php 
              $conn = oci_connect("username", "password", "url");
              $sql = 'select distinct "DRM Primary" from GIS_DATA_LOAD where "DRM Primary" is not null order by "DRM Primary" asc' ;
              $stid = oci_parse($conn, $sql);
              $success = oci_execute($stid);
              echo $success;
              while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC))
              {
                  echo "<option value=\"unit1\">" . $row['DRM Primary'] . "</option>";
              }
          ?>
      </select>
      </form>
    </td>
</tr>

// now to save the submitted form as value in a php we will use the following code

<?php
if(isset($_POST['myform']))
$selected_unit=$_POST['unit'];
?>

you can also use onselect() function ... not sure about that.. Hope it helps..thanks :)

You might want to set a unique value for each option,
else there's no telling which option was actually selected.

When you submit the form PHP will internally generate a super global array. This, as it sounds, is global and can be accessed anywhere within the script execution via variables:

  • $_POST
  • $_GET

So after submitting your form, if it is a HTTP post request then you should find your value like this:

echo $_POST['unit']; // Unit 1 etc

There are other 'superglobals'. See the documentation for more information.

Its not possible to set a variable from client side. Using AJAX to submit the form may help. It won't require the page reload.