简体   繁体   中英

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.

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

选择地区

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.

要获得计数,您将需要使用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 ;

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