0

this is more of a maths question than anything but still related.

So,

I have a basic cms that displays 4 blog posts on each page. The page number is in the url so i can get that.

I am trying to number the results using $variable++ in a foreach loop however that of course resets back to 1 when the new page is loaded.

Example for page 1:

$postNumber = 1;

foreach:
  echo "$postNumber";
  $postNumber++;
endforeach;

Now the issue comes when going to page 2.

I need to come up with a way to take the page number and then create the next set of post numbers.

So the post numbers / page numbers needed would be:

Page Number / Post start number
1 / 1
2 / 5
3 / 9
4 / 13
5 / 17
6 / 21
7 / 25
etc

The gap in between each page number / post numbers increases by 3 every time (0,3,6,9,12,15 etc)

Maths isn't my strong points, or maybe because its late... but i cant figure out a way to do this. Make sense?

Lovelock
  • 7,689
  • 19
  • 86
  • 186
  • what about pageNumber / (pageNumber - 1) * 4 + 1 – Dusan Plavak Aug 04 '14 at 20:25
  • I think that you can use $_SESSION to store the value you need between pages. Session is alive (holds the value) until the browser is open, so even if you close the related tabs, and then re-enter the page it will still remember the Post Start Number. Take a look at this: [link](http://www.w3schools.com/php/php_sessions.asp). Now, when you click NEXT / BACK you can just send a POST var and Increase / Decrease the value stored in $_SESSION. I hope it helps. Good Luck – Dawid Czerwinski Aug 04 '14 at 20:27

3 Answers3

1

Your post numbers are increased by 4 every page:

$postNumber = 1;
$pageNumber = 1;

foreach:
    echo $pageNumber, '/', $postNumber;
    $postNumber += 4;
    ++$pageNumber;
endforeach;
fiction
  • 566
  • 1
  • 6
  • 21
1

Thanks for the replies, was given the answer by a friend as this:

  $postNumber = ($pageNumber * 4) - 3;

Which works as planned.

"Simple Nth term formula"...

Lovelock
  • 7,689
  • 19
  • 86
  • 186
0

You can achieve this by using LIMIT and some basic math:

$current_page = $_GET['page']; // Or whatever   
$per_page = 4;
$start = $per_page * ($current_page - 1);

$query = 'SELECT * FROM posts LIMIT ' . $start . ',' . $per_page . ';';

Here's a link to another answer that better explains pagination and MySQL: MySQL Data - Best way to implement paging?

Community
  • 1
  • 1
The Maniac
  • 2,628
  • 3
  • 19
  • 29