繁体   English   中英

将选择选项默认设置为先前设置的选项

[英]Setting a select option default to a previously set option

在模态窗口中,我有一个选择,用户可以在其中从我的数据库中选择早餐。 通过选择并提交餐食,记录将保存在数据库中。 但是,我想实现的是,当用户进入同一模式窗口时,他们之前选择的任何餐点将作为默认选项出现。 我创建了一个查询,检查是否已选择餐食(optionquery1)。 有什么想法可以做到这一点? 谢谢

附带一提,我不确定当前是否正在设置日期php变量。 日,月和年存储在html隐藏的输入中,但不确定如何提取值。

<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<div class="modal-body">
  <form action="my_planner.php" method="post">
  <!--<span class="test5"></span>-->
  <!--<span class="test"><input type="text" name="id_disabled" value="" disabled/>-->
  <input class="test" type="text" name="id1" value="" style="text-align:center; border:0px; font-weight:bold; font-size: 25px;"/>
  <hr class="my-4">
  <input type="hidden" name="id" value=""/>
  <input type="hidden" name="month" value=""/>
  <input type="hidden" name="year" value=""/>

<br>
<p id="breakfastTag"><br>Breakfast:</p>
<select id="breakfast" name="breakfast">
<option value="" disabled selected>Select your breakast</option>
<?
$meal='breakfast';
$date='<input type="hidden" name="id" value=""/>'.'<input type="hidden" name="month" value=""/>'.'<input type="hidden" name="year" value=""/>';
$query = $db->prepare("select * from recipe_category where categoryID=1");
$query->execute();

while ($results = $query->fetch()) {
    $recipeID=$results["recipeID"];
    $query3 = $db->prepare("select * from recipe where id=:recipeID");
    $dbParams3=array('recipeID'=>$recipeID);
    $query3->execute($dbParams3);
    $breakfast = $query3->fetchAll();

    $optionquery = $db->prepare("select * from user_planner where userID=:userID and date=:date and meal=:meal");
    $optionParams= array ('userID'=>$thisUser, 'date'=>$date,'meal'=>$meal);
    $optionquery->execute($optionParams);

    while ($results12 = $optionquery->fetch()) {
        $selectedmeal = $results12['recipeID'];
    }

    $optionquery1 = $db->prepare("select * from recipe where id=:recipeID");
    $optionParams1= array ('recipeID'=>$selectedmeal);
    $optionquery1->execute($optionParams1);

    while ($results123 = $optionquery1->fetch()) {
        $selectedrecipe = $results123['name'];
    }

    foreach($breakfast as $breakfast): ?>
        <option  value="<?= $breakfast['id']; ?>"><?= $breakfast['name']; ?></option>
    <?php endforeach;} ?>
</select>

当然可以,您需要在要显示的<option>上使用selected属性。 首先从第一个<option>删除selected属性:

<option value="" disabled>Select your breakast</option>

然后在foreach循环中,您需要一个if条件:

$results123 = $optionquery1->fetch();
$selectedrecipe = $results123['id'];

foreach($breakfast as $breakfast): ?>
    <option  value="<?= $breakfast['id']; ?>" <?php if ($breakfast['id'] == $selectedrecipe) echo 'selected' ?>><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>

注意while由于我们确定Mysql仅返回一条记录( WHERE ID = <ID> ),因此我删除了while循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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