下拉选项查询sql返回重复[重复]

This question already has an answer here:

How do i stop the query for my dropdown from repeating as in the picture below?

Dropdown image

Please select CD Price:

<select name="CDPrice">
    <option value="">
        <?php
        include 'database_conn.php';
        if (!( is_object($conn) && ( get_class($conn) == 'mysqli' ))) {
            die("DB connection failure.");
        }
        $rsCDprice = mysqli_query($conn, "SELECT nmc_cd.CDPrice FROM nmc_cd");
        if (!$rsCDprice) {
            die("No result from DB query."); //probably invalid SQL, table error, etc.
        }
        if ($rsCDprice->num_rows < 1) {
            die("No rows returned from DB query."); //query runs OK, but nothing is found in DB to match.
        }
        while ($Catpriceresult = mysqli_fetch_array($rsCDprice)) {
            echo "<option value='" . $Catpriceresult[0] . "'>" . $Catpriceresult[0] . "</option>";
        }
        ?>
</select>
</div>

Try to execute below code. Please select CD Price:

<select name="CDPrice">
    <option value="">
        <?php
        include 'database_conn.php';
        if (!( is_object($conn) && ( get_class($conn) == 'mysqli' ))) {
            die("DB connection failure.");
        }
        $rsCDprice = mysqli_query($conn, "SELECT DISTINCT nmc_cd.CDPrice FROM nmc_cd");
        if (!$rsCDprice) {
            die("No result from DB query."); //probably invalid SQL, table error, etc.
        }
        if ($rsCDprice->num_rows < 1) {
            die("No rows returned from DB query."); //query runs OK, but nothing is found in DB to match.
        }
        while ($Catpriceresult = mysqli_fetch_array($rsCDprice)) {
            echo "<option value='" . $Catpriceresult[0] . "'>" . $Catpriceresult[0] . "</option>";
        }
        ?>
</select>

You can either use DISTINCT or group by for this.

  1. group by

    SELECT nmc_cd.CDPrice FROM nmc_cd GROUP BY nmc_cd.CDPrice
  2. DISTINCT

    SELECT DISTINCT nmc_cd.CDPrice FROM nmc_cd

Select DISTINCT values from the DB (unique values)

SELECT DISTINCT nmc_cd.CDPrice FROM nmc_cd

This should do it:

SELECT DISTINCT nmc_cd.CDPrice FROM nmc_cd

Good luck!!

In a table, a column may contain many duplicate values; and sometimes you only want to list the different (distinct) values.

The DISTINCT keyword can be used to return only distinct (different) values.

syntax:

 SELECT DISTINCT column_name,column_name
    FROM table_name;