Jakov Mikić
Jakov Mikić

Reputation: 979

How to create Show More Posts in PHP?

How to create that only first few posts from database are shown on a page, and after those posts you have Show More Posts button, and when you click it, it shows another few posts after the previous posts, and after that you again have Show More Posts button to show next few posts, until there is no more posts to show? Something like Facebook have or YouTube with their comments.

If in table all_posts_table I have 2 columns: id and post, this line of code will only show first 5 posts:

$posts = mysql_query("SELECT * FROM all_posts_table ORDER BY id LIMIT 5");
while ($line_posts = mysql_fetch_assoc($posts)) {
$post = $line_posts['post'];
echo $post."<br>";
}

Upvotes: 2

Views: 438

Answers (2)

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

You can use OFFSET together with LIMIT like this:

$offset = isset ($_GET['offset']) ? $_GET['offset'] : 0;
$posts = mysql_query("SELECT * FROM all_posts_table ORDER BY id LIMIT 5 OFFSET $offset");
while ($line_posts = mysql_fetch_assoc($posts)) {
    $post = $line_posts['post'];
    echo $post."<br>";
}

echo "<a href='" . $_SERVER ['REQUEST_URI'] . "?offset=".($offset + 5)."'>Next</a>";

Upvotes: 1

Benjamin M
Benjamin M

Reputation: 24527

You have to use OFFSET (or its short form: LIMIT x,y):

SELECT ... LIMIT 5 -- gives you the first 5 database entries

SELECT ... OFFSET 5 -- gives you all BUT the first 5 entries

SELECT ... LIMIT 5 OFFSET 10 -- gives you the 10 entries AFTER the first 5
SELECT ... LIMIT 5,10 -- that's the short form of LIMIT 5 OFFSET 10

Upvotes: 1

Related Questions