March 3, 2013

mySQL previous/next query

Question by StealthRT

I am trying to figure out a way to have a previous and next button to display more data for a given query-sorta like a pagination would do.

The query is this:

$query = "SELECT * 
        FROM wp_posts p
            LEFT OUTER JOIN wp_term_relationships r ON r.object_id = p.ID
            LEFT OUTER JOIN wp_term_taxonomy x ON x.term_taxonomy_id = r.term_taxonomy_id
            LEFT OUTER JOIN wp_terms t ON t.term_id = x.term_id
            LEFT JOIN wp_postmeta pm ON p.id = pm.post_id
        WHERE p.post_status = 'publish'
        AND pm.meta_key = 'xTraData'
        AND p.post_type = 'post'
        AND t.slug = 'press-coverage'
        ORDER BY p.post_date DESC LIMIT 0,6;";

How can i get the previous id and next id to use for the next/previous buttons for refreshing the query string?

Answer by Starx

You could get them using $_GET variables, which can be sent from URL. Process them to raise you limits.

A mysql limit defines how much rows to fetch and from where to fetch.

So, 0, 6 in your query say start from 0 (first) and select 6 rows.

$p_num = isset($_GET['pagenumber']) && (int)$_GET['pagenumber'] > 0 ? $_GET['pagenumber'] : 0;
$p_size = 6;

$query = "SELECT * 
        FROM wp_posts p
            LEFT OUTER JOIN wp_term_relationships r ON r.object_id = p.ID
            LEFT OUTER JOIN wp_term_taxonomy x ON x.term_taxonomy_id = r.term_taxonomy_id
            LEFT OUTER JOIN wp_terms t ON t.term_id = x.term_id
            LEFT JOIN wp_postmeta pm ON p.id = pm.post_id
        WHERE p.post_status = 'publish'
        AND pm.meta_key = 'xTraData'
        AND p.post_type = 'post'
        AND t.slug = 'press-coverage'
        ORDER BY p.post_date DESC LIMIT ".(($p_num-1) * $p_size).",".$p_size.";";

Now, send a request like: yourpage.php?pagenumber=2 and it will query the second page where a page will hold about 6 items.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!