Dropdown option query sql return repeated [duplicate]

♀尐吖头ヾ 提交于 2021-02-16 23:39:56

问题


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

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>

回答1:


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>



回答2:


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



回答3:


Select DISTINCT values from the DB (unique values)

SELECT DISTINCT nmc_cd.CDPrice FROM nmc_cd



回答4:


This should do it:

SELECT DISTINCT nmc_cd.CDPrice FROM nmc_cd

Good luck!!




回答5:


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;


来源:https://stackoverflow.com/questions/33560004/dropdown-option-query-sql-return-repeated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!