1

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.

1
  • are you using mysql_ functions, pdo, mysqli....? Commented Nov 28, 2009 at 16:28

5 Answers 5

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

SELECT DISTINCT

Comments

0

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.

4 Comments

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). ?
You mean just extracting the unique values out of an existing array, eg array_unique (php.net/manual/en/function.array-unique.php)?
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.
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!
0

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

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

Comments

0

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 ;

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.