0

I have a mysql query like this:

$topicreplycount = mysql_query('SELECT COUNT(DISTINCT post_msg_id) FROM phpbb_attachments WHERE topic_id = '.$row['topic_id'].' AND post_msg_id < '.$row['post_msg_id']);

and hope to get the result using something like this:

$topicreplycount = mysql_result($topicreplycount);

so lets say there are 4 post_msg_ids like this in the table:

2956 2957 2957 2958

and the current $row['post_msg_id'] is 2958, there are 3 post_msg_ids that are less than the one I am comparing it to, and only 2 Distinct post_msg_ids since two of them are the same, I am expecting "2" to be returned

but it doesn't seem to work, am I doing this correctly? I am not getting anything returned in the $topicreplycount variable at all using this method

I am pretty sure usign mysql_result($topicreplycount) must be wrong but don't know what to use instead

1
  • Check the query without COUNT function. Commented Apr 11, 2012 at 8:28

2 Answers 2

2

Try this:

$sql = mysql_query('SELECT COUNT(DISTINCT post_msg_id) AS num_topics FROM phpbb_attachments WHERE topic_id = '.$row['topic_id'].' AND post_msg_id < '.$row['post_msg_id']);
$result = mysql_result($sql);
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['num_topics'];
Sign up to request clarification or add additional context in comments.

1 Comment

Yes thanks Gert Van de Ven your method works but without : $row5 = mysql_result($tcount); So like this : $tcount = mysql_query('SELECT COUNT(DISTINCT post_msg_id) AS num_topics FROM phpbb_attachments WHERE topic_id = '.$row['topic_id'].' AND post_msg_id < '.$row['post_msg_id']); $row5 = mysql_fetch_array($tcount) or die(mysql_error()); echo $row5['num_topics'];
1

Using mysql_result you need to specify at least the row number so

$topicreplycount = mysql_result($topicreplycount,0);

should work. As there will only ever be one result returned because you used the COUNT() function this will be fine.

However, it is recommended NOT to use the mysql_ family of functions. They are effectively deprecated (not officially but even the PHP docs recommends not to use them). You should switch to mysqli_ or, perhaps better still, PDO.

1 Comment

cool, your method works too, even less coding plus additional handy information. So I'll have to vote this answer as the best... so what is the way to do this with PDO or mysqli?

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.