简体   繁体   中英

Print same values once in a while loop

$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.

$query = mysql_query("SELECT DISTINCT name FROM tblname");
while($fetch =mysql_fetch_array($query)) {
  echo $fetch['name'];
}

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);
$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.

$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.

Simply append them into an array like:

$items[] = $item;

After that do:

$items = array_unique($items);

After that, simply print the items.

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM