简体   繁体   English

使用mysql_fetch_array来打印逗号分隔的字符串,并使用mysql_num进行计数

[英]using mysql_fetch_array to print a comma seperated string and mysql_num to count

I am working on a project where I need to count the total number of comments on every particular post and also print the commenters id in a comma separated string. 我正在做一个项目,我需要计算每个特定帖子的评论总数,并以逗号分隔的字符串打印评论者ID。 Here is how I am taking the id of commenters and counting the comments 这是我获取评论者ID并计算评论的方式

$commenters=mysql_query("select session_id from comments where onid='theid'");
$noof_comments=mysql_num_rows($commenters); //counting the comments working good
$forprintingid=mysql_fetch_array($commenters);/* now I know this array stores all the
 session ids of commenters and I can print them by using while loop but 
   here I do not want to use any loops ..*/

The output may look like 输出可能看起来像

 total comments =$noof_comments // total comments=13
 commenters id= // it should be like 1,2,3,4,5,6,

and if any id is repeated just use them only once. 如果重复输入任何ID,请仅使用一次。 Please help me. 请帮我。 I am stuck over here may be implode is the function that may help but I dont know how exactly ...:( 我被困在这里可能是内爆的功能可能会有所帮助,但我不知道... :(

除了在PHP中完全完成它之外,您还可以在MySQL签出GROUP_CONCAT函数,该函数将根据需要提供逗号分隔的字段值。

SELECT GROUP_CONCAT(field_name) FROM table_name...

$commenters=mysql_query("select session_id from comments where onid='theid'");
$noof_comments=mysql_num_rows($commenters); //counting the comments working good
while($row=mysql_fetch_array($commenters))
$forprintingid[]=$row[0];

echo implode(',', $forprintingid); //it shoul be like 1,2,3,4,5,6,
$r = array(); while($x = mysql_fetch_assoc($commenters)) $r[] = $x; $forprintingid = implode(",",$x);

一行代码:) edit这仍然算作一行吗?

No matter what you'll need to loop. 无论您需要循环什么。 Also, you only want either a numerically indexed or associative array. 另外,您只需要一个数字索引数组或关联数组。

You can create a function: 您可以创建一个函数:

function mysql_fetch_all($result, $result_type = MYSQL_ASSOC) {
    while($rows[] = mysql_fetch_array($result, $result_type)) {} return $rows;
}

Then use implode() on the result array: 然后在结果数组上使用implode()

$forprintingid = implode(',', mysql_fetch_all($commenters));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM