Jump to content

pagination and foreach


ryan king

Recommended Posts

I know that there a million pagination tutorials online..Ive been at it for days and just cant seem to come up with a solltuon for this particular script. its searching for zips in a given radius, then comparing those zips against user zips in my database, adding that to the array and using a foreach loop then dsiplaying in a table that only allows 4 per row. How can I put pagination around all this?

 

<?php
$row_count = 0; 
$z = new zipcode_class; 
$zips = $z->get_zips_in_range($_POST['zip_code'], $_POST['miles'], _ZIPS_SORT_BY_DISTANCE_ASC, true); 

// add searched for zip to $zips array 
$zips[$_POST['zip_code']] = 0; 
$row_count = 0; 

// this is just to initialise the variable:
$result_array = array();

// first we gather all the results into a single array:
foreach ($zips as $key => $value){
//find all locations within range using returned zipcode values 
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC") or die (mysql_error()); 
while ($row = mysql_fetch_array($sql_events)) 
{
	// we just add this row to the array:
	$result_array[] = $row;
}
}
// config i guess 
$entriesperline=4;
$counter=1;
print "<table>";
// loop through each result row.
$i = 0;
foreach ($result_array As $row){

 if($counter%$entriesperline==1 && $i < 50){
	print "<tr><td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></div></td>";
}else if($counter%$entriesperline==0 && $i < 50){
	print "<td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></td></div></tr>";
}else if($i < 50){
	print "<td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></div></td>";
}
$counter++;
  $i++; 

} //exit loop

if($counter%$entriesperline!=0){
print "</tr>";
}
print "</table>";
?>

 

 

I was looking at this script I found here on phpfreaks to implement:

 

<?php   
// database connection info   
$conn = mysql_connect('localhost','dbusername','dbpass') or trigger_error("SQL", E_USER_ERROR);   
$db = mysql_select_db('dbname',$conn) or trigger_error("SQL", E_USER_ERROR);   
  
// find out how many rows are in the table    
$sql = "SELECT COUNT(*) FROM numbers";   
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);   
$r = mysql_fetch_row($result);   
$numrows = $r[0];   
  
// number of rows to show per page   
$rowsperpage = 10;   
// find out total pages   
$totalpages = ceil($numrows / $rowsperpage);   
  
// get the current page or set a default   
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {   
   // cast var as int   
   $currentpage = (int) $_GET['currentpage'];   
} else {   
   // default page num   
   $currentpage = 1;   
} // end if   
  
// if current page is greater than total pages...   
if ($currentpage > $totalpages) {   
   // set current page to last page   
   $currentpage = $totalpages;   
} // end if   
// if current page is less than first page...   
if ($currentpage < 1) {   
   // set current page to first page   
   $currentpage = 1;   
} // end if   
  
// the offset of the list, based on current page    
$offset = ($currentpage - 1) * $rowsperpage;   
  
// get the info from the db    
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";   
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);   
  
// while there are rows to be fetched...   
while ($list = mysql_fetch_assoc($result)) {   
   // echo data   
   echo $list['id'] . " : " . $list['number'] . "<br />";   
} // end while   
  
/******  build the pagination links ******/  
// range of num links to show   
$range = 3;   
  
// if not on page 1, don't show back links   
if ($currentpage > 1) {   
   // show << link to go back to page 1   
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";   
   // get previous page num   
   $prevpage = $currentpage - 1;   
   // show < link to go back to 1 page   
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";   
} // end if    
  
// loop to show links to range of pages around current page   
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {   
   // if it's a valid page number...   
   if (($x > 0) && ($x <= $totalpages)) {   
      // if we're on current page...   
      if ($x == $currentpage) {   
         // 'highlight' it but don't make a link   
         echo " [<b>$x</b>] ";   
      // if not current page...   
      } else {   
         // make it a link   
     echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";   
      } // end else   
   } // end if    
} // end for   
            
// if not on last page, show forward and last page links       
if ($currentpage != $totalpages) {   
   // get next page   
   $nextpage = $currentpage + 1;   
    // echo forward link for next page    
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";   
   // echo forward link for lastpage   
   echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";   
} // end if   
/****** end build pagination links ******/  
?>  

 

 

Thanks!

 

Link to comment
https://forums.phpfreaks.com/topic/142445-pagination-and-foreach/
Share on other sites

Ok, so i guess at the moment its outputting all the rows at once, rather than paginating them.

 

If so, you need to change your query:

"SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC"

 

and add a LIMIT on the end:

"SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT ".$startrow.",".$rowsperpage

 

$startrow is the only variable that really needs to change for it to work for each page;

 

The first $startrow would be 0 (page 1), the next page would be row 16 (page 2) (for a 4x4 grid, 16 per page), then 32 (page 3), and so on.. Obviously you will need to check if the next page of rows exist - thats extra though.

 

Apart from that all you need to do is add a next page and previous page button, maybe like:

<?php
// Get the prev page and next page. / NOTE: ont sure if that (int) part works, is for sanitization.
$prevno = (int) $_GET['page'] - 1;
$nextno = (int) $_GET['page'] + 1;

echo("<a href=\"./thispage.php?page=$prevno\">Prev</a> | 2 | <a href=\"./thispage.php?page=$nextno\">Next</a>");

?>

 

then the $startrow would be calculated like:

$startrow = (isset($_GET['page']))? $_GET['page'] * $rowsperpage : 0;

 

// isset is just there to check if "page" is "set" (isset), then you can multiply the page number by the rowsperpage to get the starting row. Otherwise the starting row should be 0 (if "page" is not specified)

 

Then declare your row (result, not actual table rows, 16 would be 4 rows, 16 / 4 columns) number.

$rowsperpage = 16; // 4x4 grid - u can change this variable to change how many each page, without having to change any of the other code.

 

This should sort you out.

I get this error..

Parse error: syntax error, unexpected ']', expecting T_STRING or T_VARIABLE or T_NUM_STRING  on line 24

 

thats this:

$result_array[] = $row;

buts its correct.

 

heres what I got:

 

<?php
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT ".$startrow.",".$rowsperpage.") or die (mysql_error()); 
while ($row = mysql_fetch_array($sql_events)) 
{
	// we just add this row to the array:
	$result_array[] = $row;
}
}
// Get the prev page and next page. / NOTE: ont sure if that (int) part works, is for sanitization.
$prevno = $_GET['page'] - 1;
$nextno = $_GET['page'] + 1;
$startrow = (isset($_GET['page']))? $_GET['page'] * $rowsperpage : 0;
$rowsperpage = 16; // 4x4 grid - u can change this variable to change how many each page, without having to change any of the other code.


// config i guess 
$entriesperline=4;
$counter=1;
print "<table>";
// loop through each result row.
$i = 0;

foreach ($result_array As $row){

 if($counter%$entriesperline==1 && $i < 50){
	print "<tr><td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></div></td>";
?>

look at the syntax highlighting i your post.... notice any colors that should be different?

 

eg, RED = a STRING.

 

 

Count your quotes/brackets/end line symbols/parenthesis. this is very basic php debugging, you will come across these errors more frequently than code. I would suggest first learning how to deal with these errors and fix them - or you might get stuck everytime ou change ur code.

I know the problem is in this string

<?php
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT ".$startrow.",".$rowsperpage.") or die (mysql_error()); 
?>

 

but for the life of me I cant figure out the proper syntax to get it to work.

 

I figured maybe I could do it like this.. but no go

<?php
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT '$startrow', '$rowsperpage'") or die (mysql_error()); 
?>

 

 

 

There is quite a bit of information on MySql statements,

 

One page about the LIMIT statement;

http://php.about.com/od/mysqlcommands/g/Limit_sql.htm

 

There are other links further down the page also, if you have any other queries for mysql :).

 

Though if you look carefully at the sql code i gave you, it is already enclosed as a string, the only thing needed is either to assign it to a variable or copy/paste into mysql_query(..here..);

 

 

like so?

 

<?php
//find all locations within range using returned zipcode values 
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT ".$startrow.",".$rowsperpage 
while ($row = mysql_fetch_array($sql_events, $startrow, $rowsperpage)) 
{
	// we just add this row to the array:
	$result_array[] = $row;
?>

close, try to understand that strings are sent as "Arguments" to a Function;

 

functions such as echo();

print();

mysql_query();

 

the argument goes inside the brackets:

 

mysql_query($arg,"argument");

 

and every event needs to end with a ;.

ok, I have been reading documentation. Im just having trouble linking all these things together.. Weve now got alot going on in our select string and I cant find much documention that goes past the basic stuff. this is what I have so far, from what I have read..it seems logical

<?php
foreach ($zips as $key => $value){
//find all locations within range using returned zipcode values 
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT `$startrow`,`$rowsperpage`")
while ($row = mysql_fetch_array($sql_events))
{
	// we just add this row to the array:
	$result_array[] = $row;

}
}
?>

 

the whole thing:

<?php 
$row_count = 0; 
$z = new zipcode_class; 
$zips = $z->get_zips_in_range($_POST['zip_code'], $_POST['miles'], _ZIPS_SORT_BY_DISTANCE_ASC, true); 

// add searched for zip to $zips array 
$zips[$_POST['zip_code']] = 0; 
$row_count = 0; 
// this is just to initialise the variable:
$result_array = array();
$prevno = $_GET['page'] - 1;
$nextno = $_GET['page'] + 1;
$startrow = (isset($_GET['page']))? $_GET['page'] * $rowsperpage : 0;
$rowsperpage = 16; // 4x4 grid - u can change this variable to change how many each page, without having to change any of the other code.


// first we gather all the results into a single array:
foreach ($zips as $key => $value){
//find all locations within range using returned zipcode values 
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT `$startrow`,`$rowsperpage`")
while ($row = mysql_fetch_array($sql_events))
{
	// we just add this row to the array:
	$result_array[] = $row;

}
}
// Get the prev page and next page. / NOTE: ont sure if that (int) part works, is for sanitization.

// config i guess 
$entriesperline=4;
$counter=1;
print "<table>";
// loop through each result row.
$i = 0;

foreach ($result_array As $row){

 if($counter%$entriesperline==1 && $i < 50){
                          echo("<a href=\"./thispage.php?page=$prevno\">Prev</a> | 2 | <a href=\"./thispage.php?page=$nextno\">Next</a>");
	print "<tr><td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></div></td>";
}else if($counter%$entriesperline==0 && $i < 50){
                echo("<a href=\"./thispage.php?page=$prevno\">Prev</a> | 2 | <a href=\"./thispage.php?page=$nextno\">Next</a>");
                	print "<td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></td></div></tr>";
}else if($i < 50){
                                echo("<a href=\"./thispage.php?page=$prevno\">Prev</a> | 2 | <a href=\"./thispage.php?page=$nextno\">Next</a>");
	print "<td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></div></td>";
}
$counter++;
  $i++; 

} //exit loop

if($counter%$entriesperline!=0){
print "</tr>";
}
print "</table>";


?>

 

getting this error now

Parse error: syntax error, unexpected T_WHILE on line 26

 

 

and every event needs to end with a ;

 

Also i made a mistake in my earlier post;

 

$startrow = (isset($_GET['page']))? $_GET['page'] * $rowsperpage : 0;

 

should be:

 

$startrow = (isset($_GET['page']) && $_GET['page'] != 0)? ($_GET['page'] - 1) * $rowsperpage : 0;

 

Becuase on page 1: "1" multiplied by "16" = 16, since you want to start from row 0 (since its the first page) you must take 1 off the page, eg;

 

page 1: (1-1) * 16 = 0; (0 * 16)

page 2: (2-1) * 16 = 16; (1 * 16)

page 3: (3-1) * 16 = 32; (2 * 16)

 

Hope that makes sense, sorry for the confusion :P

thanks for pointing that out, I replaced that code.

 

and yes, semi colon on the end of the select string like so..

<?php
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT `$startrow`,`$rowsperpage`");
?>

 

However, now I just get a blank page.

also, look more carefully at my code...

 

$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT `$startrow`,`$rowsperpage`")

 

is not the same as

 

("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT ".$startrow.",".$rowsperpage)

thats it! its limiting my results.. ofcourse its saying

 

Prev | 2 | Next

Prev | 2 | Next

Prev | 2 | Next

Prev | 2 | Next

Prev | 2 | Next

Prev | 2 | Next

Prev | 2 | Next

Prev | 2 | Next

Prev | 2 | Next

 

and the pages dont work..but I think I can fix this! Thanks for taking the time to help me learn as I code.. That helps me to better understand what Im doing!

 

ok.. my site works off of smarty templates. before we added paginiation to this script, I just included this php file into a .tpl file that I created like so

 

{assign var="title" value=$CONTENT_TITLE}
{include file="$SKIN_DIR/jr_overall_header1.tpl"}


       {include_php file="`$JAMROOM_DIR`/azippyy.php"} 



{include file="$SKIN_DIR/jr_overall_footer.tpl"}

 

 

 

Below is the php script with the zipcode stuff

<?php 

print "<link href='/skins/Cobalt/Cobalt.css' rel='stylesheet' type='text/css' media='screen'>";
require('include/jamroom-include.inc.php'); 
require_once('zipcode.class.php');      // zip code class 

$row_count = 0; 
$z = new zipcode_class; 
$zips = $z->get_zips_in_range($_POST['zip_code'], $_POST['miles'], _ZIPS_SORT_BY_DISTANCE_ASC, true); 

// add searched for zip to $zips array 
$zips[$_POST['zip_code']] = 0; 
$row_count = 0; 


$prevno = $_GET['page'] - 1;
$nextno = $_GET['page'] + 1;
$startrow = (isset($_GET['page']) && $_GET['page'] != 0)? ($_GET['page'] - 1) * $rowsperpage : 0;
$rowsperpage = 16; // 4x4 grid - u can change this variable to change how many each page, without having to change any of the other code.

// this is just to initialise the variable:
$result_array = array();

// first we gather all the results into a single array:
foreach ($zips as $key => $value){
//find all locations within range using returned zipcode values 
$sql_events = mysql_query("SELECT * FROM jamroom_band_info WHERE band_zipcode='$key' ORDER BY band_update DESC LIMIT ".$startrow.",".$rowsperpage);
while ($row = mysql_fetch_array($sql_events)) 
{
	// we just add this row to the array:
	$result_array[] = $row;
}
}
// config i guess 
$entriesperline=4;
$counter=1;
print "<table>";

// loop through each result row.
$i = 0;
foreach ($result_array As $row){

 if($counter%$entriesperline==1 && $i < 50){
                               		print "<tr><td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></div></td>";
}else if($counter%$entriesperline==0 && $i < 50){
               
                	print "<td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></td></div></tr>";
}else if($i < 50){
                                		print "<td align='center'><div class='body-zip'><a href=\"members/{$row['band_id']}\">{$row['band_name']}</a><br><a href=\"members/{$row['band_id']}\"><img border='0' src=\"image.php?band_id={$row['band_id']}&mode=band_image&width=100&theme=Sage\">{$row['band_image']}</a></div></td>";
}
$counter++;
  $i++; 

} //exit loop

if($counter%$entriesperline!=0){
print "</tr>";
echo("<a href=\"./azippyy.php?page=$prevno\">Prev</a> | ".htmlentities($_GET['page'])." | <a href=\"./azippyy.php?page=$nextno\">Next</a>"); 
}

print "</table>";

?>

 

 

So, basicly the php needs to include an overall_header and overall_footer everytime you click PREV or NEXT to cycle through results.

it is the way you are linking your pages:

 

./azippyy.php?page=$prevno

Because you need to use the smart thing (never used b4 lol) to include your file like it does normally.

 

You need to find the request string, and the filename of the smart script that u start on.

 

eg;

 

if the first page is:

index.php?smartvar=somevalue

 

then the next page would need to be:

index.php?smartvar=somevalue&page=2

 

So, you need to find the string

index.php?smartvar=somevalue

 

so that you can add this into the prev/next urls.

 

----

 

I actually use this kind of thing in a lot of my scripts, so i dont have to keep track of my arguments.

 

So i'll make a little function that should do it for us:

 

<?php

// creates a url without destroying the current one. (keeping it on the same page with the same values).
function make_url($id_list){

if(!is_Array($id_list)){
	echo("error, function make_url(arg), arg should be an array.");
	return;
}

// add each element
foreach($id_list as $id_str=>$id_val){

	if($id_val === false){ // must use ===, since if you use ==, then 0, false, and null mean the same thing.

		$url = (!isset($url))? null : $url;

		$url = str_replace(
			array(
				"&".$id_str."=".@$_GET[$id_str],
				$id_str."=".@$_GET[$id_str]."&",
				$id_str."=".@$_GET[$id_str]
				), 
			"", 
			$url
		);
	}else{
		// For the loop
		$url = (!isset($url))? $_SERVER['REQUEST_URI'] : $url;

		// if page is alread in the url somewhere get rid of it (or we will have lots of them,).
		$url = (isset($_GET[$id_str]))? str_replace(
			array(
				"&".$id_str."=".@$_GET[$id_str],
				$id_str."=".@$_GET[$id_str]."&",
				$id_str."=".@$_GET[$id_str]
				), 
			"", 
			$url
		) : $url; // the : colon is like the }else{ part of an if statement.

		$preq = (substr($url,-1) != "?")? "?" : "";

		// if there is already arguments u need to add the &, otherwise you need to add the ?.
		$url = ((count($_GET) == 1 && isset($_GET[$id_str])) || count($_GET) == 0)? $url.$preq.$id_str."=" : $url."&".$id_str."=".$id_val;
	}
}

return $url;
}

$prev = make_url(
array(
	"page"=>@$_GET['page'] - 1,
	"id"=>@$_GET['id'] + 53
)
);
$next = make_url(
array(
	"page"=>@$_GET['page'] + 1,
	"id"=>false
)
);

// Use like so.
echo("<a href=\"".$prev."\">Prev</a>");

echo(" -- ");

// Use like so
echo("<a href=\"".$next."\">Next</a>");

?>

 

You can try that snippet on its own, it will keep the same query string so it will never go to another page. Basically you use it like this:

 

make_url(array list_of_ids)

 

the array "list_of_ids" can be any number of ids. you can remove an id you dont want by setting its value to false.

 

for your use though, my example snippet should provide more than adequete.

ive noticed also, you are not solely using the query for the results. so you need to make another small function to limit the results you get from the zip query, eg:

 

<?php

Function array_limit($array,$start,$length){
$return_array = array();
for($i=$start;$i<($start + $length);$i++){
	$return_array[] = $array[$i];
}
return $return_array;
}

$zips = array_limit($zips,$startrow,$rowsperpage);

// then comes the foreach loop.

?>

 

Also, you must declare variables _before_ you use them, look at $rowsperpage; and where u put it.

This also means you can take the LIMIT etc part off the mysql query. since you aren't getting all the zips from mysql (you cant limit 1 row, since ur query is ust to find the row that matches the zip).

 

EDIT:

I know ive given you the code, it is because explaining this to your is much harder for me than giving you the code, hopefully you will revise the code and understand it, why it works, and how. Though i have not written them very reader friendly). (my answer was wrong originally so i just gave u the code to fix it rather than confusing you more)

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.