1

Hello Guys I have coma separated entries in my table. I want use DISTINCT function to get unique result. I have entries like

id | name
1  | sachin tendulkar, virat kohli, ms dhoni
2  | ms dhoni, vvs laxman, ajinkya rahane
3  | rohit sharma, virat kohli, ms dhoni

I want to use mysqli to show results like

name : sachin tendulkar, virat kohli, ms dhoni, 
       vvs laxman, ajinkya rahane, rohit sharma

I don't want to repeat these names if they are same.

I tried like :

$catquery = $db->query("SELECT DISTINCT name FROM players WHERE id='$id';");
while($row2 = $catquery->fetch_object()):
echo "$row2->name";
endwhile;

But got result like :

sachin tendulkar, virat kohli, ms dhoni 
ms dhoni, vvs laxman, ajinkya rahane 
rohit sharma, virat kohli, ms dhoni

It's not finding unique names, please help me to get it solved !!!

Salim
  • 13
  • 3

2 Answers2

0

You need to process it on PHP side.

$catquery = $db->query("SELECT name FROM players WHERE id='$id';");

$names = [];    //Collect name to this
while($row2 = $catquery->fetch_object()) {
    $pieces = explode(',',$row2->name); //explode the string by ',' character
    foreach ($pieces as $piece) {
        $names [] = trim($piece);
    }

}
var_dump(array_unique($names)); //here is the uniqe array

You can explode it by , (comma and space) if you are sure, there is always a space after comma.

If you just get back 1 row, because id is primary key, then no need the while.

vaso123
  • 12,347
  • 4
  • 34
  • 64
  • Getting error like `Fatal error: Cannot use object of type stdClass as array in ` on `$names = [];` line – Salim Jun 02 '16 at 15:01
  • Fixed this `$row2->name` – vaso123 Jun 02 '16 at 15:09
  • It worked but getting one error `Notice: Undefined variable: row2 xyz.php on line 74 Notice: Trying to get property of non-object in xyz.php on line 74 array(4) { [0]=> string(12) "Navjot Singh" [1]=> string(11) "Ashiwin Kumar" [2]=> string(12) "Amaal Mallik" [3]=> string(12) "Ramesh Tiwari" } ` I added `$names = $row2->name;` as you said – Salim Jun 02 '16 at 15:17
0

It's better to make one array and echo it one time

$unique_names = [];
$catquery = $db->query("SELECT DISTINCT name FROM players WHERE id='$id';");
while($row2 = $catquery->fetch_object()):
  $unique_names = array_merge($unique_names, array_map('trim',explode(',',$row2->name)));
endwhile;

$unique_names = array_unique($unique_names);
echo implode(',',$unique_names);

At the end, you have all unique names in $unique_names array. For instance, I imploded it and echoed. You can use it in your own way

And this is added for your request in comment:

foreach($unique_names as $unique_name){
  echo '<a href="/player.php?player='. str_replace(' ','-',$unique_name) .'">'.$unique_name.'</a><br>';
}
Mojtaba
  • 4,852
  • 5
  • 21
  • 38