user3599194
user3599194

Reputation: 19

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. 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

Answers (4)

AbraCadaver
AbraCadaver

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

I wrestled a bear once.
I wrestled a bear once.

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

raidenace
raidenace

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

Alexey Palamar
Alexey Palamar

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

Related Questions