views:

196

answers:

4

Hi,

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.

A: 

SELECT DISTINCT

PurplePilot
A: 

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.

Kaleb Brasee
Thanks,In fact i already use a query to show the results, so i would like to use an array so to store the unique values (so dont to do a second array).?
Manolis
You mean just extracting the unique values out of an existing array, eg array_unique (http://php.net/manual/en/function.array-unique.php)?
K Prime
Yeah, if you only want to use the original query, you'll need to 1) create an array consisting of all the names in your original query (basically how Cletus demonstrated), then 2) use the array_unique function that K Prime posted to remove duplicates from that array.
Kaleb Brasee
Yes,but could you explain it more?Look,the query is eg: $query = dquery('SELECT * FROM POSTS'); (the real table has more columns so thats why i write *) and then:foreach ($query as $res){echo ''; etc..}After this i want to display eg:echo 'People who posted:..';how could i add them at the array,but only 1 time and to display directly the name? thanks!
Manolis
A: 

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);
cletus
A: 

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

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

Paul Creasey