Reputation: 423
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?
Upvotes: 0
Views: 3344
Reputation: 774
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>";
Upvotes: 0
Reputation: 429
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>
Upvotes: 2
Reputation: 414
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>
Upvotes: 3
Reputation: 191729
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.
Upvotes: 0