2
$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
$name = $fetch['name'];

echo "$name";

}

In my example, after echoing out $name in a while, the values are:

Carrots
Lemon
Carrots
Lemon

Is there a way to not repeat printing the same value that will look like this:

Carrots
Lemon

Thank you very much.

1

7 Answers 7

7
$query = mysql_query("SELECT DISTINCT name FROM tblname");
while($fetch =mysql_fetch_array($query)) {
  echo $fetch['name'];
}
Sign up to request clarification or add additional context in comments.

Comments

2

SQL Solution:

SELECT DISTINCT `name` FROM tblname;

or

SELECT `name` FROM tblname GROUP BY `name`;

PHP Solution:

$my_array = array();
$query = mysql_query("SELECT * FROM tblname");

while($fetch =mysql_fetch_array($query)) {
    $my_array[] = $fetch['name'];
}

$my_array = array_unique($my_array);

echo implode('<br />', $my_array);

Comments

1
$names = array();
$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
  $name = $fetch['name'];

  if (!in_array($name,$names)){
    echo "$name"; 
    $names[] = $name;
  }
}

Will work.

Comments

1
$sql = mysql_query("SELECT DISTINCT  table1.id, table2.id, table2.name 
FROM table1, table2 WHERE id=id GROUP BY name");

This Will Work 100% sure. SET GROUP BY name and DISTINCT. If not it is not working.

Comments

0

Simply append them into an array like:

$items[] = $item;

After that do:

$items = array_unique($items);

After that, simply print the items.

Comments

0

You can fetch them all into an array and then run array_unique()

$query = mysql_query("SELECT * FROM tblname");
$arr = array();
while($fetch =mysql_fetch_array($query)) {
  $arr[] = $fetch;
}

$output = array_unique($arr);
foreach ($output as $uniqe_val) {
   echo $unique_val;
}

Comments

0

I find the question ambiguous. I think you're asking for what appears in How to make a list of unique items from a column w/ repeats in PHP SQL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.