简体   繁体   中英

mySQL previous/next query

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?

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.

You could pass in variables for the LIMIT bounds. In this instance previous id would be null and next id could be 7. If you always want X records at a time you could do LIMIT $next_ID, ($next_ID + $X) and modify your previous and next variables accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM