Selecting Individual Values In A Database With MySql (DISTINCT) In Joomla

Wanted to show you how easy it is to use the DISTINCT function in MySQL inside of Joomla.

This is very useful whenever you want to create a list of all the individual values of a specific field in a database table. It only gets that value once, so like below, there is several “Burlington” values in the city field.

Table: jos_locations

idnamecitystate
1Coffee HouseGrahamNC
2Barnes & NobileBurlingtonNC
3SheetzMebaneNC
4StarbucksBurlingtonNC
5PaneraBurlingtonNC

So this is how you would use distinct to just grab that list of specific values.

<?php
  // get a database object
  $db = &JFactory::getDBO();
  $query = 'SELECT DISTINCT city FROM #__locations';
?>

Now we want to set the query.

<?php
  $db->setQuery($query);
?>

Finally we send the query and return the results and print it out.

<?php
  $results = $db->loadObjectList();
  print_r($results);
?>

The results will be in an object oriented list like this:

array(
  [0] => stdClass Object ([city] => Graham)
  [1] => stdClass Object ([city] => Burlington)
  [2] => stdClass Object ([city] => Mebane)
)

NOTICE: Burlington is only shown 1 time, not 3!

So let me know what you think, and hope this helped!