简体   繁体   中英

Select Option inside value with php

I have a trouble about select option value choosing with PHP

Multiple select box is showing for state and city. Jquery loads as ajax method for database. And I need to reach "option value" inside value. I will show the problem inside below codes.

   <?php  
     function load_country() {

     include 'includes/db.php';

    $sql = "SELECT * FROM ilce ORDER BY name";

    mysqli_set_charset($con, "UTF8");

    $result = mysqli_query($con, $sql);

    while($row = mysqli_fetch_array($result)) {
      $output .= '<option name="' . $row['name'] .'" value="' . 
      $row["ilce_id"].'">' . $row["name"]. '</option>';
    }

    return $output;

   }
  ?>

   <select class="form-control" name="state" id="state">
     <option>Choose State</option>
      <?php
        echo load_country();
      ?>
    </select>

    <?php 
      $state = mysqli_real_escape_string($con, $_POST['state']);  
      echo $state;

     ?>

 <option value="5">New York</option>
 $state is showing for me Example : "id" => 5

Thus, I want to reach "New York", inside value. Please help me Thanks

The text content of an <option> element is not posted to the server, only its value .

If you're inserting the selected state into a database (like in a user table), you might just insert the numeric state ID and join the two tables when you need to display the information.

Alternatively, you can fetch an array of all states indexed by their IDs and then reference that array:

while ($row = mysqli_fetch_array($result)) {
  $allStates[$row['ilce_id']] = $row['name'];
}

$stateId = $_POST['state'];
$thisState = $allStates[$stateId];
echo $thisState;

Or just fetch the one row that you need by its ID, depending on what you need.


A less desirable solution is to set the <option> value to the row's name rather than its ID:

$output .= '<option value="' . $row["name"] . '">' . $row["name"] . '</option>';

But that seems to defeat the purpose of using a relational database.


Also see Get Text From Tag Using PHP .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM