填充从数据库中选择字段 [英] Populating Select Field from Database

查看:166
本文介绍了填充从数据库中选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用PHP填充选择字段。问题是我不知道如何显示它们,因为我得到一个值在数据库中显示两次,因为我回应它作为选择,然后循环它的所有结果。如何显示 selected 匹配字段值,然后显示所有不匹配的选择

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

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>

返回的内容

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


推荐答案

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

Skip the row if the value matches the first one.

一个片段:

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

这篇关于填充从数据库中选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆