[RESOLVED] Avoiding Loop Requests
Results 1 to 3 of 3

Thread: [RESOLVED] Avoiding Loop Requests

  1. #1
    Aspiring PHP Ninja ScottyBoy's Avatar
    Join Date
    Jun 2011

    resolved [RESOLVED] Avoiding Loop Requests

    I'm having a little trouble here, and I'm not even sure if it's possible to do this without using a ton of queries. Hopefully you guys can guide me to a more optimized solution here.

    Here's the table to start with. It's from a forum software.

    | id_msg | id_topic | id_board | id_member | poster_name | poster_time |

    What I need to do here is get a list of everyone who posted within a certain time (poster_name and poster_time) and then count how many times they posted in that time. The only way I can figure to do this is to first get the list:

    SELECT id_member, poster_name
    FROM messages
    WHERE poster_time > UNIX_TIMESTAMP('some time')
        AND poster_time < UNIX_TIMESTAMP('some other time');
    And then loop through the people to find out how many times they posted and create the output.

    PHP Code:
    foreach ($people as $person)
    // Note that in real life, all the data is checked and sanitized.
    $sql '
        SELECT COUNT(*) AS total
        FROM messages
        WHERE id_member = '
    $person['id'], ';';

    $list[] = $person['name'] . ': ' $total;

    It seems to me there should be a way to combine the queries and avoid the loop completely. It's not that big a deal if there are only a couple of people to loop through, but if there are a few hundred, this is nowhere near an optimized approach.

  2. #2
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    General Systems Vehicle "Running Gear"
    Use a GROUP BY clause to group the counts by id_member.

    It might be a little hairy if you can have different poster_name values for each id_member value because you don't say which poster_name value you want returned in that case. If, on the other hand, there is only one possible poster_name for each id_member value, then poster_name probably shouldn't be in that table to begin with.
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  3. #3
    Aspiring PHP Ninja ScottyBoy's Avatar
    Join Date
    Jun 2011
    Dude! Thanks a lot, man, that is so awesome. Problem solved.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts