MySQL数据库中预先选择的下拉列表值

时间:2016-11-20 13:12:05

标签: php html mysql

虽然我已经研究过,但我找不到任何解决办法。我需要将数据库值(“Default”)作为下拉列表的预选值。

<select name="listCustomer" id="listCustomer">
    <?php 
    $sql = mysqli_query($connection,"SELECT customer_name FROM customers");
    while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)){
    echo "<option value=\"" .   $row['customer_name'] . "\">" . $row['customer_name'] . "</option>";}
    ?>
</select>

你可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

只需在echo之前创建一个变量,例如:

$selected = ((strtolower($row['customer_name']) == 'default') ? 'selected' : '');

然后将回声更改为:

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

答案 1 :(得分:1)

这可以使用customer_name

上的if语句来完成
$sql = mysqli_query($connection,"SELECT customer_name FROM customers");
while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)){
     if($row["customer_name"] === "Default"){
      echo "<option value=\"" .   $row['customer_name'] . "\" selected>" . $row['customer_name'] . "</option>";
     } else {
       echo "<option value=\"" .   $row['customer_name'] . "\">" . $row['customer_name'] . "</option>";
     }
 }
 ?>

注意第一个回声上的选定标记。

答案 2 :(得分:0)

$query="SELECT customer_name FROM customers";
$result = @mysql_query ($query);
echo "<select name=customer_name value=' '>";
while($drop=@mysql_fetch_array($result)){
echo "<option value=$drop[customer_name]>$drop[customer_name]</option>";
}
echo "</select>";