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
https://forums.phpfreaks.com/topic/95091-pagination-with-while/#findComment-487317
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
https://forums.phpfreaks.com/topic/95091-pagination-with-while/#findComment-487323
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.