Ruchika Ruchika - 1 year ago 96
MySQL Question

How to use Distinct Function through PHP in displaying unique value

how to display only Distinct values through PHP - so that the resultant output is unique

The distinct function is not having any impact on this line

#__new_categories.cat_name as cat_name

Here is the complete code

$db = JFactory::getDBO();
$query = $db->getQuery(true);
$c = $item->prod_cat_id;

$query = "SELECT
DISTINCT #__new_categories.cat_name as cat_name
, #__new_categories.cat_parent as cat_parent
, #__new_products.prod_name as prod_name
from #__new_categories
inner join #__new_products on #__new_products.prod_cat_id =
where #__new_products.prod_cat_id = $c";

$results = $db->loadObjectList();
foreach($results as $row){
echo $row->cat_name;

When echoing in cat_name is displaying similar values like

Honda Honda Honda Honda Honda Honda

Ford Ford Ford Ford Ford Ford

How to use Distinct Function in

echo $row->cat_name;

Answer Source

The problem comes from the inner join.

You can do something like this with your query:

GROUP BY #__new_categories.cat_name

or to handle this with PHP, because this will most probably break your query:

$results = $db->loadObjectList();  
$uniqueValues = array();
foreach($results as $row){
    if (!isset($uniqueValues[$row->cat_name])) {
        echo $row->cat_name;
        $uniqueValues[$row->cat_name] = true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download