Calculate number of pages using PHP Maths and Round
I have a given number of potential posts. We don't know how many there are but the system is set up to show 12 per page. Alon开发者_如何学JAVAg the bottom I would like it to display the number of pages.
So first if we get the posts:
<?php $pages = get_posts('category_name=news'); ?>
Now what we want to do is
- work out how many posts it has found
- divide that number by 12
- round that number up to the nearest whole number (UP never down)
- divide that number by 1 and give how many times 1 goes into it.
- thus giving as many page numbers as needed.
The ideas is to have them lined up as 1 | 2 | 3 | 4 | 5 etc..
Any ideas?
You're over thinking it. If you know the number of results and the max number of results per page, then you know how many pages you need. I suppose this is WordPress because you've used get_posts, so that should return an array containing the posts, so:
<?php
$max_per_page = 12; //Max results per page
$posts = get_posts('category_name=news');
$total_posts = count($posts); //Total number of posts returned
$pages = ceil($total_posts / $max_per_page);
for($i = 1;$i <= $pages;$i++)
{
echo '<a href="?page=' . $i . '">' . $i . '</a>'; //Or whatever the link needs to be
if($i != $pages)
{
echo "|"
}
}
?>
work out how many posts it has found
SELECT COUNT(*) FROM *table* WHERE *conditions*...
divide that number by 12
SELECT COUNT(*)/12 AS num_pages FROM *table* WHERE *conditions*...
OR
$count = mysql_query(*see #1*)/12.0; // NOT JUST 12!
round that number up to the nearest whole number (UP never down)
$count = ceil($count);
divide that number by 1 and give how many times 1 goes into it.
REALLY?? DIVIDING ANY NUMBER BY 1 RETURNS ITSELF!
thus giving as many page numbers as needed.
Not really. How would you know what particular page the user is currently on? How do you plan on actually paginating posts? If the posts are already populated, you are wasting 1-2 queries every time, just for your pagination.
You are basically trying to make pagination, but without knowing a lot of SQL, you're better off using an existing solution (or at least re-factor the existing code to limit queries)
精彩评论