在填充的PHP下拉列表中选择匹配的值

时间:2013-03-19 03:31:15

标签: php mysql wordpress-plugin

我已经设法通过从MySQL获取的php创建填充的下拉列表。代码#1

// START FUNCTION: create a drop down list containing area options from saved area in database
function create_dropdown_areanames() {
    global $wpdb;
    $output = '';
    $tbl_ads = $wpdb->prefix . "awpcp_areas";

    $query="SELECT DISTINCT area_name FROM ".$tbl_ads." WHERE area_name <> '' ORDER by area_name ASC";
    $res = awpcp_query($query, __LINE__);

    $listofsavedareas = array();
    while ($rsrow=mysql_fetch_row($res)) {
        $listofsavedareas[] = $rsrow[0];
    }
    $savedareaslist = $listofsavedareas;

    foreach ($savedareaslist as $savedarea) {
        $output .= "<option value=\"" . esc_attr($savedarea) . "\">" . stripslashes($savedarea) . "</option>";
    }
    return $output;
}
// END FUNCTION: create a drop down list containing area options from saved area in database

然后我通过Code#2

调用了这个函数
        $allareas = create_dropdown_areanames($adcontact_country);

然后我通过代码#3

在页面中显示它
$theformbody.="<select name=\"adarea\" onchange=\"changeareameo();\" id='add_new_ad_area'><option value=\"\">";
$theformbody.=__("Area","AWPCP");
$theformbody.="</option>$allareas</select></p>";

我想将下面的代码添加到代码#1

$output .= "<option selected='selected' value=\"" . esc_attr($savedarea) . "\">" . stripslashes($savedarea) . "</option>";

所以在触发函数$ allareas = create_dropdown_areanames($ adcontact_country)时; IF $ adcontact_country变量与数据库字符串匹配,它将是在下拉列表中选择的变量,否则下拉列表将从上到下生成。提前致谢

1 个答案:

答案 0 :(得分:1)

只需在foreach中添加三元运算符。

 foreach ($savedareaslist as $savedarea) {
        $output .= "<option ".($savedarea==$adcontact_country?'selected="selected" ':'')."value=\"" . esc_attr($savedarea) . "\">" . stripslashes($savedarea) . "</option>";
    }

将变量添加到函数参数

function create_dropdown_areanames($adcontact_country=null) {