• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 644
  • Last Modified:

How do you omit duplicate entries from the list created in php?

I have got some PHP code that populates a list based on entries found within a MySQL database.
It is successfully creating the list, but I was wondering how to omit the duplicate entries.
I would also like them listed alphabetically.
Eventually users will select from the values available, so duplicates are not meant to be there and setting it up alphabetically is user friendly.
Thanks..the code is attached.!
Populating a list box
include("Settings.php"); //Path to Settings.php
$sql= "SELECT * FROM event";
$result = mysql_query($sql) or die("Sql Query Failed: " . mysql_error());
$ListOptions = "";
while ($row = mysql_fetch_array($result)) {
        //The following line creates the <option></option> tags for the <select> list
        $ListOptions .= "\t<option value='" . $row["ID"] . "'>" . $row["EventType"] . "</option>\n";
<select name='MyList'>
<option value="0" selected>Select EventType</option>
<?php echo $ListOptions; ?>

Open in new window

Amanda Watson
Amanda Watson
  • 2
1 Solution
To sort them alphabetically, change your SQL statement from 'SELECT * from event' to 'SELECT * from event ORDER BY EventType' f.ex.

To avoid having duplicate entries in the database I'd suggest to create a primary key or unique column in the database itself. That way, no duplicate entries can be written to the database as a primary key or a column marked as unique assures that there are no duplicate values in it.

If you already have duplicate values in it and want to show possible duplicate values only once, you can use:

SELECT * from event GROUP BY EventType ORDER BY EventType

That way you will only get unique entries reported.

You might even want to change the primary key from ID (what it is probably at the moment) to EventType, therefore it's impossible to add duplicate entries into this table.

Amanda WatsonWeb DeveloperAuthor Commented:
Thanks, that great.
Thanks for your help!
You're welcome.
Will try to answer your other question too in a few minutes, please don't forget to assign points if the solution is acceptable for you.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now