从数据库填充选择字段

时间:2013-03-31 19:16:52

标签: php database loops select echo

我正在尝试使用PHP填充select字段。问题是我无法弄清楚如何显示它们,因为我在数据库中显示两次值匹配,因为我将它作为选中回显然后将所有结果循环。如何只显示匹配字段值的selected,然后显示与所选字符值不匹配的所有值?

TABLE CATEGORIES

cat_id  cat_name
1       soccer
2       baseball
3       basketball

表格文章

art_id art_cat_id
1      1

PHP / HTML

<select name="category">
<?php
    $sql = "SELECT cat_id cat_name, art_id, art_cat_id 
            FROM categories LEFT JOIN articles
            ON categories.cat_id = articles.art_cat_id
            WHERE art_id = 1";
    $result = query($sql);

    if($result===false) {
        echo("Query Fail");
    }
    else {
        ?>
        <option value="<?php echo $data['art_cat_id'] ?>" selected="selected"><?php echo $data['cat_name'] ?></option>
        <?php
        while( $data = mysqli_fetch_array($result)) {

        ?>     
        <option value="<?php echo $data['cat_id'] ?>"><?php echo $data['cat_name'] ?></option>
        <?php
        }
    }
    ?>
</select>

返回的内容

<select name="category">
    <option value="1" selected="selected">soccer</option>
    <option value="1">soccer</option>
    <option value="2">baseball</option>
    <option value="3">basketball</option>
</select>

我在寻找什么

<select name="category">
    <option value="1" selected="selected">soccer</option>
    <option value="2">baseball</option>
    <option value="3">basketball</option>
</select>

1 个答案:

答案 0 :(得分:3)

如果值与第一行匹配,则跳过该行。

摘录:

    ?>
    <option value="<?php echo $data['art_cat_id'] ?>" selected="selected"><?php echo $data['cat_name'] ?></option>
    <?php
    while( $data = mysqli_fetch_array($result)) {
        if ($data['art_cat_id'] == $data['cat_id']) continue;
    ?>     
    <option value="<?php echo $data['cat_id'] ?>"><?php echo $data['cat_name'] ?></option>
    <?php
    }