Probably really simple.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Moargazm
Forum Newbie
Posts: 6
Joined: Fri Oct 31, 2008 2:08 pm

Probably really simple.

Post 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)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Probably really simple.

Post 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.
Moargazm
Forum Newbie
Posts: 6
Joined: Fri Oct 31, 2008 2:08 pm

Re: Probably really simple.

Post by Moargazm »

I'm sorry, I don't exactly understand how to put this together, can you give me a full example?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Probably really simple.

Post 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
Moargazm
Forum Newbie
Posts: 6
Joined: Fri Oct 31, 2008 2:08 pm

Re: Probably really simple.

Post by Moargazm »

Thanks!

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