Reputation: 19
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. Here is how I am taking the id of commenters and counting the comments
$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. Please help me. I am stuck over here may be implode is the function that may help but I dont know how exactly ...:(
Upvotes: 0
Views: 945
Reputation: 78994
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:
$forprintingid = implode(',', mysql_fetch_all($commenters));
Upvotes: 1
Reputation: 23379
$r = array(); while($x = mysql_fetch_assoc($commenters)) $r[] = $x; $forprintingid = implode(",",$x);
one line of code :) edit Does this still count as one line?
Upvotes: 1
Reputation: 12836
Instead of doing it fully in PHP, you can also check out GROUP_CONCAT
function in MySQL
which will give comma separated field values as you need.
SELECT GROUP_CONCAT(field_name) FROM table_name...
Upvotes: 2
Reputation: 1430
$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,
Upvotes: 1