Calculate number of pages using PHP Maths and Round - php

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. Along 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 '' . $i . ''; //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)

Related

Multiple pages for results

On my search engine I get results via xml from blekko.com
I use: http://blekko.com/ws/?q=google/rss
And adding: &p= *number*
I can get different pages of results, e.g.
Page 1, 1 - 15 results
Page 2, 15 - 30 results
Like at the bottom of google, however I also get a number of total results
With those two (total & page number) is there any way to generate the right amount of links at the bottom for a next button, page1 results, page 2 results ect...
$count is the total and there are 15 results per page
If I understand you correctly you want something like:
for($i; $i<10 && $i<$totalPages; $i++)
{
echo ''.$i.'';
}
?
Not sure of what you want to do but usually to create links to different pages of results you need the total number of results and the nb of results you want to display per page. You then make a simple division to get the number of pages.

Displaying results hyperlink numbers like a search engine

Does anyone know of a good resource on how to create the hyperlink numbers at the bottom of a results page as search engines do to load the next number of results?
The page would load the first 10 results. And then if you click on the number, it loads corresponding results in that 10 number range.
Example:
0-10 -> show no numbers
11-20 -> show 1, 2
21-30 -> 1, 2, 3
up to 50
anything more than 50 does 1,2,3,4,5.....67 [last number].
My thoughts so far (I'm doing this in PHP/mysqli but the logic is more important than the code):
$total = mysqli_num_rows($result) //total number of reqults from sql query
if ($total>10) {
$last = intval($total/10) + 1 //get the last number of the results
if($last <= 5){
for ($i, $i<$last, $i++){
//print the numbers as hyperlinks
} else {
//print 1 through 5 ... then $last
}
}
This though is static from only 1-5...last number while the search engines have it so if you click on the number, it remembers that number and bases the new logic on it. So if I click on the 5 in my formula, it should change to something like:
[previous] 3,4,5,6,7....67 [next]
And then I would just pass the number to the page itself again and limit the results based on what number was passed. Any suggestions also on the best way to pass the info?
You are looking for a pagination script. Visit this link The page is in Arabic but forth post is of pagination and you can download source for english or arabic version of pagination
Basically, you need two values to create a pagination, a limit and a offset.
1.The limit is the amount of items your are displaying at the same time.
2.The offset is from where you started your query.
So, let's say you have 5 items in each page and 25 items total.
In your query, you have to limit 5,0 (the amount of items and the position the query will start).
Now, if you divide 5(limit)/25(total) and you'll get 5 (amount of pages).
Now in page 0 (the start) you can get the offset by multiplying the page number with the limit, so 0 (page) * 5 (limit) gives you 0 (in the first page you start from the offset 0).
Now in the 3rd page, you multiply 3(page) * 5 (limit) it gives you 15, which means in page 3 (or four if you take into account that you actually started at page 0) you will display from offset 16 to 20.
Finally in page 4 (which to your users will be page 5 because they started at page 1, not page 0) you will display from offset 21 to 25 which are all the items in your query.

How to do greater (>) and lesser (<) scripts?

I am using this script below. I need the "next" to show only when there are more than 10 entries.
code:
$fetch = mysql_query("SELECT * FROM table LIMIT $startrow, 10")or
die(mysql_error());
/*
this next options shows regarldess if there are more than 10 queries or less.
How can i make it so that it shows only when there are more than 10 queries.
*/
echo 'Next';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous';
You need to perform a separate query to count the number of rows in the table: SELECT COUNT(*) FROM table, and check if the returned number is greater than 10 $startrow + 10.
A word of advice. Don't rewrite something that's been done a thousand times. What you are trying to accomplish is called Pagination (Page by page displaying of data). It's commonly part of most PHP frameworks; such as CodeIgniter or CakePHP. There are also plugin classes out there which will help you greatly.
Google Search:
http://www.google.com/search?q=php+pagination
As other have already mentioned you'll typically need two queries. One query for the subset of results (number per page & an offset point) and one query for the total number of results. Try to find an existing class to help you with your paginating.
Good luck, Jeff Walters

updating post views each time a post is viewed with php

I don't know if this is allowed, but I need clarification on a solution given to a question.
What is the best way to count page views in PHP/MySQL?
I have the exact question. I just have no idea how the solution makes any sense, here is the solution:
$sample_rate = 100;
if(mt_rand(1,$sample_rate) == 1) {
$query = mysql_query(" UPDATE posts
SET views = views + {$sample_rate}
WHERE id = '{$id}' ");
// execute query, etc
}
Any help?
Here mt_rand() generate random number between 1 to 100, so probability of that number to be one is 1/100.
If this generate 1, we are increasing value of views by 100.
So, effective increase in database per view
= ( Probability of increasing view ) * (increase in database )
= (1/ 100 )* 100
= 1
So in long run it will increase database value by 1 for each view.
This is tread-off between accuracy of post and speed. As MySQL query are more time extensive than PHP rand function calls.
For each user that views a page, a random number between 1 and 100 ($sample_rate) is generated. If the number equals 1, then the database is updated by the amount of possible values (sample rate).
This is simply a sampling technique used to save resources. This is a common technique used for larger websites.
If you are running a smaller operation, you should simply update the database each time the page is viewed, as oppose to using a sampling method.

How to perform page control?

I mean what the most efficient way to get information about the quantity of your page's items and make sql query with LIMIT that you need. or I should get all items and then crop array with php functions?
now I do 2 queries: first to count all items and second to get items that I need with LIMIT.
OK, I'll be more concrete. For example I need to show a question on my page and 20 answers to this question. At the bottom there shold be page control: links to the next, prev page and so on. I want to show proper number of links (number of answers/20) and when I go to any link I want to recieve proper answers (for example 41 to 60 on the 3d page). So what's the best way to get number of items (answers) to show proper number of links and to get proper answers for each link?
I guess your'e trying to say you want to know how many items/answers there is in the query but only read up to 20 items at at time, for pagination.
Firstly: You really should look for a pagination package; lots and lots of people have had the same problem before and there probably exists both free/opensource and proprietary solutions for your programming language and framework. (If you say what language you are using I'm sure someone can reccomend a solution for you.)
Anyway, I know I like to know how things work, so this is how it usually does:
As far as I know the pagination code calculates the pages by doing one query using select count(*) from tblX where something divide this number with the items-per-page number and use ceiling (e.g. 4.1 => 5).
For listing the results per page a new query is required; don't worry the count query is terribly much faster than getting every result discarding the ones you don't need DO NOT DO THAT (that's the recipie for becoming the top story on this page). Something like select * from tblX where something limit Y offset Z where Y is the number of items per page, and Z is the the (requested_page - 1)*Y; page 1 will have offset 0, page 2 have offset 20 (if thats what Y are) etc..
But do not try to implement this manually, it's unneccesary, tedious and error prone, much better to use your time customizing a readymade solution.
I'm assuming you want a count of the number of rows you'll be reading so as to do some pagination or similar? I don't understand your need for the LIMIT in the context of your question. However, if you just want a count of how many rows have been found, use one of the following.
You select the count of all rows such as:
select count(*) as counted, name, address
from contact
Or found rows:
SELECT SQL_CALC_FOUND_ROWS, name, address
from contact
This may be mysql specific I'm not sure.
Update:
For pagination you would do something like the following - (Psuedocode)
$rows = array($result)
$num_rows = sql_calc_found_rows
$per_page = 20
$pages = ceil($num_rows / $per_page)
page
$rows_this_page = array()
$rows_this_page = get_values($rows, (min index)$page_number * $per_page - $per_page, (max index)$page_number * $per_page - 1)

Categories