Page 1 of 1

Probably really simple.

Posted: Fri Oct 31, 2008 2:21 pm
by Moargazm
I'm pretty new to php, and I just need someone to explain how to do this.

Let's say I have a page called "comments.php", and the layout that matters is like this:

Code: Select all

 
$sql = mysql_query("SELECT * FROM comments ORDER BY lastpost DESC");
 
while($r = mysql_fetch_array($sql)) {
 
echo "$thefreakingcomments";
}
What I want to do is only have it echo each comment 50 times, and then dynamically create another page, and another for every 50 (ie. comments.php?page=2)

Re: Probably really simple.

Posted: Fri Oct 31, 2008 2:38 pm
by requinix
There are a billion ways to do what you want - which is called "pagination" by the way.

First, figure out how many comments there are.
A

Code: Select all

SELECT COUNT(*) FROM comments
is the usual solution. From this you can know how many pages there will be: number of comments / comments per page, rounded up.

Then you figure out what page you're on, and change your query to

Code: Select all

SELECT ... LIMIT $start, $count
where $count is the number of comments per page and $start is (page number - 1) * $count.

That's it.

Re: Probably really simple.

Posted: Fri Oct 31, 2008 2:43 pm
by Moargazm
I'm sorry, I don't exactly understand how to put this together, can you give me a full example?

Re: Probably really simple.

Posted: Fri Oct 31, 2008 3:06 pm
by requinix

Code: Select all

<?php
 
// $page: page number
$page = (isset($_GET["page"]) ? intval($_GET["page"]) : 1);
if ($page < 1) $page = 1; // adjust if it's too small
 
// $count: number of comments per page
$count = 50;
 
// $comments: total number of comments
list($comments) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM comments"));
// $pages: number of pages of comments
$pages = ceil($comments / $count);
 
if ($page > $pages) $page = $pages; // adjust if it's too large
 
$start = ($page - 1) * $count;
$sql = mysql_query("SELECT * FROM comments ORDER BY lastpost DESC LIMIT $start, $count");
while ($r = mysql_fetch_array($sql)) {
    echo "the freaking comments";
}
 
Now you need some way to navigate between pages. Couple hints:
- If $page == 1 then there's no Previous link
- If $page == $pages then there's no Next link

Re: Probably really simple.

Posted: Fri Oct 31, 2008 3:47 pm
by Moargazm
Thanks!

Edit, removed problem: Nevermind, all I had to do was remove (ORDER BY lastpost DESC) and it works fine.