Jump to content

Pagination with while


rofl90

Recommended Posts

	<?php
$sql = "SELECT * FROM NEWS ORDER BY id ASC";
$query = mysql_query($sql);

$total = mysql_num_rows($query);
$maxnews = '3';
if($total > $maxnews)
{
//what do i put here??????
}
else{
while($result = mysql_fetch_array($query)) {
// echo news articles if total is no greater than 3
}
}
?>

 

I have this so far, anyone care to fill in the "What do I put here"?

Link to comment
Share on other sites

You should never pull more data from mysql than you need....  It's just silly....  What if you had 10k rows and pulled all of them just for like 3 rows?

 

You should limit it with sql LIMIT.

 

Example:

 


$page = (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > = 1) ? $_GET['page'] : 1;

$per_page = 5;

$count_q = mysql_query("SELECT COUNT(id) FROM news");
$count_r = mysql_fetch_row($count_q);
$count = $count_r[0];

if($page > ceil($count/per_page)) $page = 1;


$limit_min = ($page-1)*$per_page;
$query = mysql_query("SELECT * FROM news ORDER BY id ASC LIMIT {$limit_min}, {$per_page}");
while($r = mysql_fetch_assoc($query)) {
     //echo out the contents
}

 

 

The count isn't exactly the best thing in the world, but you need it so you can know whether or not to have a next button.

 

(I guess you could do another limit and see if there were a result instead of a count.... hmmmm....  I don't paginate much lol)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.