Skip to content
Advertisement

Select option only posts id, I need the value too

I have an issue in a simple PHP MySQL project. When I try to fetch a record from a select option, it only gives me the id. I want the value from the select to be passed too.

<form class="form-style-9" method="POST" action="function.php?type=updatedistrict">``
    <ul>
    <li>ID:
      <input type="hidden" name="dist_id"  class="field-style field-full align-none"  value="<?php echo $ids;?>" readonly />

    </li>
    <li>District Name:
    <input type="text" name="name" class="field-style field-full align-none" value="<?php echo $names;?>" />
    </li>
    <li>Postal Code:
    <input type="text" name="code" class="field-style field-full align-none" value="<?php echo $codes;?>"/>
    </li>
    <li>Province
    <select name="province_id" class="form-control">
      <option value="">Select Province</option>
      <?php
      $sql = mysqli_query($conn, "SELECT id, province From province");
      $row = mysqli_num_rows($sql);
      while ($row = mysqli_fetch_array($sql)){
      echo "<option value='". $row['id'] ."'>" .$row['province'] ."</option>" ;
      }
      ?>
      </select>

    <li>
    <input type="submit" value="Update" name="submit" />
    </li>
    </ul>
    </form>

This is the update function code:

case 'updateprovince':
if (isset($_POST['submit'])) {
          $id = $_POST['dist_id'];
          $prov_id= $_POST['province_id'];
          

          $query=$conn->query("UPDATE province SET province='$prov_id' where id='$id'");
          if ($query) {
            echo '<script> window.location.replace("province.php");
                  </script>';
          }

          else
          {
            echo "issue";
          }
      }


break;

Advertisement

Answer

You can post your province name instead of the id this way:

echo "<option value='". $row['province'] ."'>" .$row['province'] ."</option>" ;

Your $_POST['province_id'] will then contain the province value instead of the current id.

A way to pass along both the id and the value (in case you need to retain the id for some additional processing) through your option would be this:

echo "<option value='". $row['id'] . '|'. $row['province'] ."'>" .$row['province'] ."</option>" ;

Then after the submit, you’d simply split the two by the ‘|’ delimiter.

if (isset($_POST['submit'])) {
    $id = $_POST['dist_id'];
    $province = explode('|', $_POST['province_id']);
    $province_id = $province[0]
    $province_name = $province[1]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement