Page 1 of 1

only print certain number of rows

Posted: Wed Apr 20, 2005 2:13 pm
by Jr
Ok I'm pulling rows from a database and printing information from each row when it prints. I am just wondering how I can only print a certain number of rows (15 or so) and make a link that lets me click 'next' or whatever and go to the next 15 or so rows.

Posted: Wed Apr 20, 2005 2:19 pm
by nigma
Do a google search for "pagination" with php. You'll definitely find some tutorials in the first page of results that explains how to do what you want.

Posted: Mon Apr 25, 2005 1:06 pm
by Jr
Ok... this is what I came up with but for some reason it wont show me more results when I click on one of the page numbers or next it doesn't show the 'prev' button or anymore results. Then when I click on the '1' page to go back to the results I have already been shown it doesn't show those anymore either. Help? Please? Anyone?

Code: Select all

<?
	/* Set current, prev and next page */
	$page = (!isset($_GET['page']))? 1 : $_GET['page']; 
	$prev = ($page - 1); 
	$next = ($page + 1); 
	
	/* Max results per page */ 
	$max_results = 5; 
	
	/* Calculate the offset */ 
	$from = (($page * $max_results) - $max_results); 
	
	/* Query the db for total results. You need to edit the sql to fit your needs */ 
	$result = mysql_query("select id from members"); 
	
	$total_results = mysql_num_rows($result); 
	
	$total_pages = ceil($total_results / $max_results); 
	
	$pagination = ''; 
	
	/* Create a PREV link if there is one */ 
	if($page > 1) 
	{ 
	$pagination .= '<a href="test.php?page='.$prev.'">Previous</a> '; 
	} 
	
	/* Loop through the total pages */ 
	for($i = 1; $i <= $total_pages; $i++) 
	{ 
	if(($page) == $i) 
	{ 
	$pagination .= $i; 
	} 
	else 
	{ 
	$pagination .= "<a href=\"test.php?page='$i'\">$i</a>"; 
	} 
	} 
	
	/* Print NEXT link if there is one */ 
	if($page < $total_pages)
	{ 
	$pagination .= "<a href=\"test.php?page='$next'\">Next</a>"; 
	} 
	
	/* Now we have our pagination links in a variable($pagination) ready to print to the page. I pu it in a variable because you may want to show them at the top and bottom of the page */ 
	
	/* Below is how you query the db for ONLY the results for the current page */ 
	$result=mysql_query("select * 
	from members 
	LIMIT $from, $max_results "); 
	
	while ($i = mysql_fetch_array($result)) 
	{ 
		print "<table>";
			print "<tr>";
				print "<td>$i[user_name]</td>";
				print "<td>$i[pass]</td>";
			print "</tr>";
		print "</table>";
	} 
		print "<table>";
			print "<tr>";
				print "<td>$pagination</td>";
			print "</tr>";
		print "</table>";
?>
Jcart | Please review :arrow: Posting Code in the Forums