将多个选项标记为已选择,数据库结果

时间:2017-01-25 09:02:24

标签: php mysql

我有两个表格,post_languages(列:languageIDlanguageName)和post_to_languageslanguageIDpostID)和一个选择形式。

我想使用数据库中的结果标记languageID选择的一个或多个选项标记。不想只显示语言,我想将它们标记为从post_languages表提供的语言列表中选择。

我尝试了但只选择了一种语言,$res只返回一个ID:

$stmt = $db->prepare('SELECT languageID FROM post_to_languages WHERE postID = :postID');
$stmt->execute(array(':postID'=>$postID));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt2 = $db->prepare('SELECT languageID, languageName FROM post_languages ORDER BY languageName');
$stmt2->execute();
echo '<select class="post-language form-control" name="postLangID[]" multiple="multiple" required>';
while($row2 = $stmt2->fetch()){
    foreach ($result as $res) {
        if ($row2['languageID'] == $res) {
            $selected = 'selected';
        } else {
            $selected = '';
        }                      
    } 
    echo '<option value="'.$row2['languageID'].'" '.$selected.'>'.$row2['languageName'].'</option>';
}
echo '</select>';

1 个答案:

答案 0 :(得分:1)

第一个原因是$stmt查询。您已通过postID字段进行过滤。 第二个是$res变量的类型,我认为它是array。请尝试var_dump。 我觉得它看起来像是:

foreach ($result as $res) {
        if ($row2['languageID'] == $res['languageID']) {
            $selected = 'selected';
        } else {
        $selected = '';
    }                      
} 

如果$postIDArray,您也可以尝试以下代码:

$place_holders = implode(',', array_fill(0, count($postID), '?'));
$stmt = $db->prepare("SELECT languageID, languageName, IF(post_languages.languageID IN (SELECT post_to_languages.languageID FROM post_to_languages WHERE post_to_languages.postID IN ($place_holders)), 1, 0) as selected FROM post_languages ORDER BY languageName");
$stmt->execute($postID);
echo '<select class="post-language form-control" name="postLangID[]" multiple="multiple" required>';
while ($row = $stmt->fetch()) {
    if ($row["selected"]) {
      echo '<option value="'.$row['languageID'].'" selected>'.$row['languageName'].'</option>';
    } else {
      echo '<option value="'.$row['languageID'].'">'.$row['languageName'].'</option>';
    }
}
echo '</select>';