Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating Select Field from Database

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>
like image 465
user2201765 Avatar asked Aug 01 '26 05:08

user2201765


1 Answers

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
    }
like image 157
Joe Frambach Avatar answered Aug 03 '26 18:08

Joe Frambach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!