我有两个表,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>';

最佳答案

第一个原因是$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>';

关于php - 将多个选项标记为选中的数据库结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41847297/

10-10 08:54