0

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?

0

4 Answers 4

3

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.