0

I'm trying to create a dropdown list of my product type from the database, I'm using this code from How to populate HTML dropdown list with values from database.

<select name="product_type">
<?php 
include('include/conn.php');
$sql = mysql_query("SELECT product_type FROM produk2");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"product_type1\">" . $row['product_type'] . "</option>";
}

?>
</select>

I'm going to add this in my search engine, but the dropdown from that code making it read all data from product_type. Is it possible to create the dropdown without the same product_type twice?

Community
  • 1
  • 1
Mohd Fadli
  • 143
  • 10
  • 4
    Add `DISTINCT` to the query? – Rasclatt Sep 09 '15 at 03:07
  • 1
    You are looking for distinct result. You could use DISTINCT or GROUP BY. By the way, you should at least use mysqli or even better, PDO. – Osh Mansor Sep 09 '15 at 03:08
  • try this `SELECT DISTINCT product_type FROM produk2` – J Santosh Sep 09 '15 at 03:10
  • Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide. – Luke Sep 09 '15 at 04:43

1 Answers1

1

You should at least connect using mysqli :

conn.php =

 $con=mysqli_connect("server","username","password","database");
            // Check connection
            if (mysqli_connect_errno())
            {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }

Then your query file :

   <select name="product_type">
<?php 
include('include/conn.php');
$sql = mysqli_query($con,"SELECT product_type FROM produk2 GROUP BY product_type")
while ($row = mysqli_fetch_array($sql)){
echo "<option value=\"product_type1\">" . $row['product_type'] . "</option>";
}

?>
</select>