dpcyx08288 2017-04-12 10:17
浏览 27
已采纳

PHP打印下拉列表,默认情况下从中间选择

I have a dropdown list that works fine, but halfway through the list of 80 values is the one I want as selected by default

$cosOptions = cos_options();

Is the variable

<td><select name="options"><?php print $cosOptions; ?></select></td>

Prints the dropdown, then the function below.

function cos_options()
{
    $dbh = dbh_get();
    $options = '';

    $sql = 'select code, descr FROM cos';
    $stmt = $dbh->prepare($sql);
    $stmt->execute();
    while (true) {
        $r = $stmt->fetch();
        if (is_bool($r)) break;
        $options .= '<option value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
    }

    dbh_free($dbh);
    return $options;
}

The Postgres table only has two columns and 80 rows

code descr

D1 Pizza

D2 Bread

D3 Cornflakes etc,.

What I need is D43 Rice to be selected at first because 90% of the time it will be this. How can I achieve this? I've gone through a bunch of posts on here but can't get it working.

  • 写回答

3条回答 默认 最新

  • dongpu4141 2017-04-12 10:27
    关注
    function cos_options()
    {
    $dbh = dbh_get();
    $options = '';
    
    $sql = 'select code, descr FROM cos';
    $stmt = $dbh->prepare($sql);
    $stmt->execute();
    while (true) {
        $r = $stmt->fetch();
        if (is_bool($r)) break;
        $temp=$r['code']. ' '. $r['descr'];
        if($temp=="D43 Rice") //check for whatever you want to set selected
        {
        $options .= '<option selected value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
        }
        else
        {
        $options .= '<option value="' . $r['code'] . ' ' . $r['descr'] . '">' . $r['code'] . ' ' . $r['descr'] . '</option>';
        } 
    }
    
    dbh_free($dbh);
    return $options;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效