简体   繁体   中英

option select by based on the value from db with php

How can I select the option based on the value from db with php .For example;

<select>
  <option value="1">Val1</option>
  <option value="2">Val2</option>
  <option value="3">Val3</option>
  <option value="4">Val4</option>
  <option value="5">Val5</option>
</select> 

when value=3 change

<option value="3" selected="selected">Val3</option>

How can I do this with php&mysql?

You need something like

<?
   $values = array(); // array from DB
   $selectedKey = 10; // some key
?>
<select>
   <? foreach ($values as $key => $value) { ?>
      <option value="<?=$key?>" <?= $key==$selectedKey ? 'selected' : ''?>> <?=$value?> </option>
   <? } ?>
</select>

Hope This Helps

<select>
    <?php
    $value = 3; // Desired Value
    $sql ='' ;// sql to get values from mysql
    $res = mysql_query($sql);
    while($row=mysql_fetch_array($res))
    {?>
     <option value="<?php echo $row['id'];?>" <?phh if($row['id']==$value)echo "selected='selected'"  ; ?> ><?php echo $row['name']; ?></option>
    <?php }
    ?>
</select>

In the loop that prints out the possible values, compare each value to the value acquired from the DB. If they match, add the selected attribute.

First give the select tag a name.

<select name="name">

Get the table rows through a mysql_query into $row_set array
If say the value to be searched for is $search

while($row = mysql_fetch_array($row_set))
if($row['column_name']==$search) echo "<option value='{$row['value']}' selected='selected'>{$row['name']}</option>";

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