问题
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.
group by
SELECT nmc_cd.CDPrice FROM nmc_cd GROUP BY nmc_cd.CDPrice
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