选择下拉列表中选择的名称

时间:2016-04-25 07:19:06

标签: php mysql pdo while-loop

从上帝的桌子中挑选上帝

$sth =$dbh->prepare("SELECT god_id,god_name_ml,god_name_en,image,info_ml,info_en,details_ml,
       details_en,rounds_ml,rounds_en,mantra_ml,mantra_en,display_order FROM god");
       $sth->execute();

从deity table查询select deity.Here god_id是来自god table的外键

   $stmt = $dbh->prepare("SELECT deity_id,god_id,deity_name_ml,deity_name_en,info_ml,info_en,details_ml,
      details_en,mantra_ml,mantra_en,display_order FROM deity
      WHERE deity_id = :deity_id");
    $stmt->bindValue(':deity_id',$deity_id,PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll();
    $temp_array=$result[0];
    $god_id=$temp_array['god_id'];

显示从神桌下拉列表中显示神的代码

<?php while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { ?>
       <option value="<?php echo $row['god_id'];?>">
         <?php echo $row['god_name_en']; ?>
       </option>
       <?php } ?>
       </option>
   </select>

我需要的是,在下拉列表中,神表中给定的god_id存在于deity表中,使其成为选中状态。 只有我需要被选中Id被选中

3 个答案:

答案 0 :(得分:1)

只需检查ID是否相同,试试这个:

<?php while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { ?>
  <option <?php if($row['god_id'] == $god_id) { echo "selected='selected'"; } ?> value="<?php echo $row['god_id'];?>"><?php echo $row['god_name_en']; ?></option>
<?php } ?>
</option>
</select>

答案 1 :(得分:0)

试试这个:

<?php while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { ?>
  <option <?php if($row['id'] == $stmt->god_id) { echo "selected='selected'"; } ?> value="<?php echo $row['god_id'];?>"><?php echo $row['god_name_en']; ?></option>
<?php } ?>
                                          </option>
                                        </select>

答案 2 :(得分:0)

当您编写每个选项时,比较God表中的God_I'd是否与当前选项的god_ID匹配。如果它确实在值后追加“选定”文本。

所以选中的选项看起来像

<option value='1' selected>foo</option>