Multiple database query?

yo2lux - July 3, 2008 - 22:39

I need to obtain how many threads exist on forum:

function _forumstat_fetch() {
  $sql = "SELECT COUNT(*) AS nthreads FROM {node} WHERE status=1 AND type='forum'";
  $res = db_query($sql);
  $item = db_fetch_object($res);
  return $item;
}

The code work pretty good, I get the number in $item->nthreads;

Now I want to obtain how many post (comments) exist on forum. I need to put a separate SQL query for this purpose? But db_fetch_object($res) accept only one query :(

Someone know which is the best way to solve this problem ? I appreciate any idea! Thanks

Are you trying to count the

yuriy.babenko - July 3, 2008 - 22:50

Are you trying to count the total number of forums and total number of comments ACROSS all forums? Or number of comments in EACH forum? Should this number contain the original post or only replies?
---
Yuriy Babenko
www.yubastudios.com

Are you trying to count the

yo2lux - July 3, 2008 - 23:01

Are you trying to count the total number of forums and total number of comments ACROSS all forums?
Yes. I need to know how many threads and comments exist in whole forum.
A forum statistics like:

Threads: 4, Posts: 14, Members: 2

Now I don't know exactly, I need a separate SQL query to obtain each data? Much query not hurt?

A simple way would be to

yuriy.babenko - July 3, 2008 - 23:49

A simple way would be to simply make two queries, but...

<?php
$result
= db_query("SELECT COUNT(threads) AS threads, SUM(comments) AS comments
                FROM    (
                        SELECT n.nid as threads,
                               COUNT(c.nid) as comments
                        FROM        {node} n
                        LEFT JOIN    {comments} c
                            ON    n.nid = c.nid
                        WHERE    n.type = 'forum'
                        AND        n.status = 1
                        GROUP BY    n.nid
                    ) AS results
            "
);
   
$item = array();
   
    if(
mysql_num_rows($result) > 0)
       
$item = db_fetch_object($result);
       
    return
$item;
?>

And you can access the data by:

<?php
$item
->threads;
$item->comments;
?>

---
Yuriy Babenko
www.yubastudios.com

thanks for your help! Is

yo2lux - July 4, 2008 - 09:48

thanks for your help!
Is possible to put a second query result in "$items" object? (for example: a second query to obtain number of users), or which is the best way to handle this situation ? Thanks again !

 
 

Drupal is a registered trademark of Dries Buytaert.