Always query certain number of posts

Discussion in 'PHP' started by levani, Sep 8, 2009.

  1. #1
    Hello,

    I need small help with php. This is my code which queries latest 5 post title from database. I would like to query commented and uncommented posts separately and wrote this code:

    <?php
    		global $wpdb;
    		$posts = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_author = $id AND post_type = 'post' LIMIT 5 ");
    		foreach ($posts as $post) {
    
    		if ($post->comment_count >= 1) {
    		echo '<li>' . $post->post_title . '</li>';
    			}
    		else if ($post->comment_count < 1) {
    		echo '<li>' . $post->post_title . '</li>';
    			}
    		} 
    		?>
    PHP:
    But there is one big problem. If the latest five posts are all uncommented when I view commented posts it doesn't display anything. I know that it happens because of comparing comments number to 1 and showing posts only after it, but I don't know any better ways.

    Can anyone please help?
     
    levani, Sep 8, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Uh you're putting them both in the same <ul>.. I see no difference between your if and else, the code is exactly the same: <li>$post->post_title</li> ..

    So you need to do two separate queries:

    Add " AND comment_count = 0 " for uncommented posts, and " AND comment_count > 0 " to get the commented posts.
     
    premiumscripts, Sep 8, 2009 IP
  3. acifmanzoor

    acifmanzoor Peon

    Messages:
    317
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    wow i was searching a same thing and i found it very helpful.thanks
     
    acifmanzoor, Sep 8, 2009 IP
  4. autouch

    autouch Peon

    Messages:
    17
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You don't need to put separate queries. You can do it in one query.

    
    SELECT * FROM wp_posts WHERE post_author = $id AND post_type = 'post' AND post_comment > 1 LIMIT 5 UNION SELECT * FROM wp_posts WHERE post_author = $id AND post_type = 'post' AND post_comment = 0 LIMIT 5 
    
    Code (markup):
    The reason why you don't want to split it into 2 queries is because it's more efficient to put it in one query (it's faster performance)
     
    autouch, Sep 8, 2009 IP
  5. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Yeah, I just suggested two queries because it's going to be easier for him to integrate that in two different <ul> - but yeah, yours is faster.
     
    premiumscripts, Sep 8, 2009 IP