Question

I would like to create an array (in php) from sql results like this: We have the sql-table "Posts" which stores the Name and the Message.Example:

Name | Message

John | Hello

Nick | nice day

George | Good bye

John | where

What i want is to output the names of people who have posted a message but dont display the same names more than 1 time. So the output would be John,Nick,George. (From these records, we see that John has posted 2 messages, but at the final output, we see only one time his name).

Is this somehow possible? Thanks in advance.

Was it helpful?

Solution

Try:

$sql = <<<END
SELECT DISTINCT Name FROM Posts
END;
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$names = array();
while ($row = mysql_fetch_array($query)) {
  $names[] = $row[0];
}
print_r($names);

OTHER TIPS

SELECT DISTINCT

You could run a SQL query to just select the distinct names, and nothing else:

SELECT DISTINCT Name FROM Posts;

This will give you a result set consisting of distinct Names values, with each unique value only being returned 1 time in the set.

to get the count you will need to aggregate using group by:

SELECT NAME , COUNT(*) as Posts FROM Posts GROUP BY NAME

Here is the SQL if you are not averse to group BY

select count(name) as N, name from posts group by name ;

People having more than 1 post

select count(name) as N, name from posts group by name having N > 1 ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top