Populating Select Field from Database

2019-07-06 14:46发布

I'm trying to populate a select field with PHP. The problem is I can't figure out how to display them because I'm getting the one that's value matches in the database showing up twice because I'm echoing it as selected and then looping it all the results. How can I just display the selected one that matched the fields value and then all the ones that don't match the selected one?

TABLE CATEGORIES

cat_id  cat_name
1       soccer
2       baseball
3       basketball

TABLE ARTICLES

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>

What it's returning

<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>

What I'm looking for

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

1条回答
狗以群分
2楼-- · 2019-07-06 15:12

Skip the row if the value matches the first one.

A snippet:

    ?>
    <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
    }
查看更多
登录 后发表回答