Manolis
Manolis

Reputation: 57

Sql results into php array

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.

Upvotes: 1

Views: 10924

Answers (5)

rjha94
rjha94

Reputation: 4318

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 ;

Upvotes: 0

Paul Creasey
Paul Creasey

Reputation: 28864

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

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

Upvotes: 0

cletus
cletus

Reputation: 625227

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

Upvotes: 1

Kaleb Brasee
Kaleb Brasee

Reputation: 51955

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.

Upvotes: 0

PurplePilot
PurplePilot

Reputation: 6612

SELECT DISTINCT

Upvotes: 0

Related Questions