Title: Help learner understanding a query
Last modified: August 20, 2016

---

# Help learner understanding a query

 *  Resolved [Damien](https://wordpress.org/support/users/takster/)
 * (@takster)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/)
 * I’m trying to figure a custom loop out from here so I can use pagination but 
   unsure what I’ve done wrong. I’m trying to pull the top rated posts rom a database
   table and order them by votes.
 * Is my sql wrong? it works in another loop, but one that does not paginate. Thanks
   for any advice.
 *     ```
       <?php
       global $wpdb;
       $total = "SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count";
       $totalposts = $wpdb->get_results($total, OBJECT);
       $ppp = intval(get_query_var('posts_per_page'));
       $wp_query->found_posts = count($totalposts);
       $wp_query->max_num_pages = ceil($wp_query->found_posts / $ppp);
       $on_page = intval(get_query_var('paged'));
       if($on_page == 0){ $on_page = 1; }
       $offset = ($on_page-1) * $ppp;
       $wp_query->request = "SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count DESC LIMIT $ppp OFFSET $offset";
       $pageposts = $wpdb->get_results($wp_query->request, OBJECT);?>
   
       <?php if ($pageposts): ?>
         <?php foreach ($pageposts as $post): ?>
           <?php setup_postdata($post); ?>
   
           <h1><?php the_title(); ?></h1>
   
       	<?php endforeach; ?>
           <?php else : ?>
           <p>No matching entries found.</p>
           <?php endif; ?>
       ```
   

Viewing 9 replies - 1 through 9 (of 9 total)

 *  Thread Starter [Damien](https://wordpress.org/support/users/takster/)
 * (@takster)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111588)
 * well it paginates so thats a start :p
 * still unable to pull content though
 *  [Grubbyseismic](https://wordpress.org/support/users/grubbyseismic/)
 * (@grubbyseismic)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111664)
 * Since I’m (kind of) feeling my way in the dark here, I’m guessing you need to
   think about the code from the `if` statement onwards.
 * You’ve brought the relevant data forward by accessing your variable `$pageposts`.
 * Logic dictates if there’s just blank space showing up, rather than the error 
   message: `No matching entries found.` then you need to think about how the data
   you are pulling is being formatted…
 * Are you seeing the error, the result of the `<?php else : ?>` statement?
 *  Thread Starter [Damien](https://wordpress.org/support/users/takster/)
 * (@takster)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111767)
 * using the code above returns a blank page, no errors, although the pagination
   is there and the correct number of pages are displayed, so I’m guessing my query
   is structured wrong.
 *     ```
       $total = "SELECT like_pid
       FROM $wpdb->likes_count
       ORDER BY like_count";
       ```
   
 * changing to the above returns `No matching entries found.` and kills the pagination.
   I use the same SQL in a previous loop that worked, but without pagination.
 *     ```
       <?php global $wpdb;
       $query_sql = "SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count DESC LIMIT 6 OFFSET 0";
       $query_result = $wpdb->get_col( $wpdb->prepare ($query_sql, OBJECT));
       if ($query_result) {
       foreach ($query_result as $post_id) {
       $post = &get_post( $post_id );
       setup_postdata($post); ?>
   
       <-- do content  -->
   
       <?php endif;?>
       ```
   
 *  [Grubbyseismic](https://wordpress.org/support/users/grubbyseismic/)
 * (@grubbyseismic)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111791)
 * Hmmm. Well, you know categorically that your code is working!
    I know that because
   before you just weren’t getting any “useable” data. If you should go back to 
   using this version of your code, make sure there’s enough HTML surrounding your
   results so that you can rule that out as the problem. Now at least the logic 
   is holding up, as you’re only seeing what’s after the `<?php else : ?>` statement.
   Basically, it may not seem like it, but you’ve made some small progress!
 * It may not help much, but try putting a space inbetween the `."` and the first`
   likes_count`. SQL is really picky about that kind of formatting.
 * By the way, you can also add more code after the `<?php else : ?>`, possibly 
   including the query you used? Might help with further debugging. You can always
   take it out again later when this is fixed!
 * If you look carefully at the old code (for a minute), that you used “in a previous
   loop that worked, but without pagination”, you should see it will be configured
   specifically for the database installed and filled by that project.
    Reusing 
   the same code will only work if the titles of your columns in that database (
   your “field names” to use proper SQL-syntax) are identical, so ostensibly you’d
   be using the same database again. Which is unlikely, unless you’ve made copies
   and installed them yourself?
 * Are you sure you’re using the right field names?
 * You can find out the exact contents of the database your code is accessing by
   logging into it with PHPMyAdmin, for example. You will need to know how to access
   your hosting control panel, but I don’t know how your project is installed.
    
   Anyway. I strongly recommend you copy/paste the titles of the field names you
   want from there. Then at least you’re eliminating the possibility of a typo screwing
   your code.
 * I have to say I don’t envy what you’re trying to do. Errors like this are a big
   part of the reason that WP officianados stipulate that SQL should be avoided 
   wherever possible! I too may have to ignore that premise for a client soon…
 *  [Grubbyseismic](https://wordpress.org/support/users/grubbyseismic/)
 * (@grubbyseismic)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111812)
 * I’ve got another (more instructive) point of reference: the WordPress Codex. 
   I have no idea if you’ve read this already…
 * There is an entire page dedicated to the wpdb class; have a look:
 * [http://codex.wordpress.org/Class_Reference/wpdb](http://codex.wordpress.org/Class_Reference/wpdb)
 *  Thread Starter [Damien](https://wordpress.org/support/users/takster/)
 * (@takster)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111819)
 * Thanks for pointing a few helping hints out.
 * I’ve gotten to the point now where my content is displayed correctly, and in 
   the right order according to the DB query. Also pagination now works, the correct
   number of pages are being counted, this I am 100% sure of through experimentation
   with the select query.
 * However, the $ppp posts per page is not being respected and instead of showing
   6 posts per page, I get all three pages worth on one. I have my “blog pages to
   show at most” set at 6.
 * Thus my quest now is why is posts_per_page is out of whack.
 *     ```
       <?php
       global $wpdb;
       $query_sql = "SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count DESC";
       $totalposts = $wpdb->get_results($query_sql, OBJECT);
       $ppp = intval(get_query_var('posts_per_page'));
       $wp_query->found_posts = count($totalposts);
       $wp_query->max_num_pages = ceil($wp_query->found_posts / $ppp);
       $on_page = intval(get_query_var('paged'));
       if($on_page == 0){ $on_page = 1; }
       $offset = ($on_page-1) * $ppp;
       $wp_query->request = "SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count DESC LIMIT $ppp OFFSET $offset";
       $pageposts = $wpdb->get_col( $wpdb->prepare ($query_sql, OBJECT));
       if ($pageposts) {
       foreach ($pageposts as $posts) {
       $post = &get_post( $posts );
       setup_postdata($post); ?>
   
       <h1><?php the_title(); ?></h1>
   
       <?php } ?>
       <?php } ?>
       ```
   
 * Is ending the loop in this fashion the problem?
 *  [Grubbyseismic](https://wordpress.org/support/users/grubbyseismic/)
 * (@grubbyseismic)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111827)
 * Good to hear I’m helping!
 * I also think yes: your use of The Loop is definitely what to look at next; or
   rather what you’re feeding into it…
 * Your `$ppp` variable is meant to dictate exactly how many posts are “paged”, 
   yes?
 * Observe:
    `$ppp = intval(get_query_var('posts_per_page'));`
 * From the latest code, I see you’re querying the `posts_per_page` variable (as
   above), but what you’ve missed out on with this code is the opportunity to actually
   _dictate_ what that variable could be…
 * From [http://codex.wordpress.org/Function_Reference/query_posts](http://codex.wordpress.org/Function_Reference/query_posts):
   `
   query_posts( array( 'category__and' => array(1,3), 'posts_per_page' => 2, 'orderby'
   => 'title', 'order' => 'DESC' ) );`
 * Therefore, your code _could_ read:
    `$ppp = get_query_var('posts_per_page' =>
   6);`
 * Bear in mind I have done no tests on the above code, if it doesn’t work feel 
   free to do some more experimentation…
 * Also:
    `$offset = ($on_page-1) * $ppp;`
 * The above will most likely always produce a result of 0 (zero) because of the
   line before:
    `if($on_page == 0){ $on_page = 1; }`
 * Also, should you wish to see exactly what the database errors are (if there are
   any), set `$wpdb`‘s `show_errors` property to true.
    If you do choose this option,
   Make Sure You Turn It Off Again When You’re Finished (its default value is false).
 *  Thread Starter [Damien](https://wordpress.org/support/users/takster/)
 * (@takster)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111878)
 * solved! went down a different path and it’s worked a treat 🙂
 * order by `post__in`!
    [http://wordpress.org/extend/plugins/sort-query-by-post-in/](http://wordpress.org/extend/plugins/sort-query-by-post-in/)
 *     ```
       function sort_query_by_post_in( $sortby, $thequery ) {
       	if ( !empty($thequery->query['post__in']) && isset($thequery->query['orderby']) && $thequery->query['orderby'] == 'post__in' )
       		$sortby = "find_in_set(ID, '" . implode( ',', $thequery->query['post__in'] ) . "')";
       	    return $sortby;
       }
       ```
   
 *     ```
       <?php
        global $wpdb;
       $my_posts = $wpdb->get_col("SELECT like_pid FROM wp_likes_count ORDER BY like_count DESC");
       $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
       $args = array(
           'post__in' => $my_posts,
           'paged' => $paged,
           'posts_per_page' => 9,
           'orderby' => 'post__in'
           );
       query_posts($args); ?>
   
       <?php while (have_posts()) : the_post(); ?>
       <-- do a barrel roll -->
       <?php endwhile; ?>
       ```
   
 * Thanks for the help along the way Grubbyseismic!
 *  [Grubbyseismic](https://wordpress.org/support/users/grubbyseismic/)
 * (@grubbyseismic)
 * [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111883)
 * Just wanted to say: no problem! Glad you got it sorted.

Viewing 9 replies - 1 through 9 (of 9 total)

The topic ‘Help learner understanding a query’ is closed to new replies.

 * In: [Hacks](https://wordpress.org/support/forum/plugins-and-hacks/hacks/)
 * 9 replies
 * 2 participants
 * Last reply from: [Grubbyseismic](https://wordpress.org/support/users/grubbyseismic/)
 * Last activity: [15 years ago](https://wordpress.org/support/topic/help-learner-understanding-a-query/#post-2111883)
 * Status: resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
