This script will display a previous next script that will look like this:
<< prev 1 2 3 4 5 next >>
It is clean, and avoids large numbers of pages in the prev/next links

$server = "localhost";
$user = "username";
$pass = "password";
$databasename = "yourDBname";
$db = mysql_connect($server, $user, $pass);
	mysql_select_db($databasename,$db);

		$sql = "SELECT * FROM yourtable WHERE yourconditions ORDER BY your_order ";
		$query = mysql_query($sql,$db);
		$total_results = mysql_num_rows($query);
		$limit = "15"; //limit of archived results per page.
		$total_pages = ceil($total_results / $limit); //total number of pages
if (empty($page))
	{
		$page = "1"; //default page if none is selected
	}
$offset = ($page - 1) * $limit; //starting number for displaying results out of DB

	$query = "SELECT * FROM yourtable WHERE yourconditions ORDER BY your_order LIMIT $offset, $limit";
	$result = mysql_query($query);
//This is the start of the normal results...

	while ($row = mysql_fetch_array($result))
		{
			// display your results as you see fit here.
		}
		mysql_close();


// This is the Previous/Next Navigation
echo "<font face=Verdana size=1>";
echo "Pages:($total_pages)&nbsp;&nbsp;"; // total pages
if ($page != 1)
{
echo "<a href=$PHP_SELF?page=1><< First</a>&nbsp;&nbsp;&nbsp;"; // First Page Link
$prevpage = $page - 1;
echo "&nbsp;<a href=$PHP_SELF?page=$prevpage><<</a>&nbsp;"; // Previous Page Link
}
    	if ($page == $total_pages) 
			{
      			$to = $total_pages;
    		} 
		elseif ($page == $total_pages-1) 
			{
      			$to = $page+1;
    		} 
		elseif ($page == $total_pages-2) 
			{
     		 	$to = $page+2;
    		} 
		else 
			{
      			$to = $page+3;
    		}
    	if ($page == 1 || $page == 2 || $page == 3) 
			{
      			$from = 1;
    		} 
		else 
			{
      			$from = $page-3;
    		}
			
for ($i = $from; $i <= $to; $i++)

	{
	if ($i == $total_results) $to=$total_results;
	if ($i != $page)
		{
		echo "<a href=$PHP_SELF?showold=yes&page=$i>$i</a>";
		}
	else
		{
		echo "<b><font face=Verdana size=2>[$i]</font></b>";
		}
	if ($i != $total_pages)
		echo "&nbsp;";
	}
if ($page != $total_pages)
{
$nextpage = $page + 1;
echo "&nbsp;<a href=$PHP_SELF?page=$nextpage>>></a>&nbsp;"; // Next Page Link
echo "&nbsp;&nbsp;&nbsp;<a href=$PHP_SELF?page=$total_pages>Last >></a>"; // Last Page Link
}
echo "</font>";

// This is the end of the Previous/Next Navigation

I'll definitely redo this one soon, and comment the code a little better

I'm still waiting on your redo ;) The only reason I'm asking is because inscissor was over at my house the other day and we were talking about how he just set up something like this on a php site he was working on ... so it reminded me.

Yeah I remember this. It's a good thing that he pasted his code because I don't think one site exists that shows how to do this. Especially this clean. It's rare.

hi all, first of all, thank you! this is a very nice script..

I am no coder, i basically do a little bit of php, i try :) hehe

My question is, how to display the results correctly? Let me tell you the situation:

I have a table named "screenshots" with names/date of files in it and i want to "echo" the names of the files correctly. I know my english is terrible, im sorry.

heres what ive tried:

<?php
include('config.php');
$db = mysql_connect($dbserver, $dbuser, $dbpass); 
	mysql_select_db($dbname,$db); 
		$sql = "SELECT id,big,thumb,postdate, DATE_FORMAT(postdate, '%d/%m/%Y @ %T ') AS pdate FROM screenshots ORDER BY id DESC"; 
		$query = mysql_query($sql,$db); 
		$total_results = mysql_num_rows($query); 
		$limit = "12"; //limit of archived results per page. 
		$total_pages = ceil($total_results / $limit); //total number of pages
 
if (empty($page)) 
	{ 
		$page = "1"; //default page if none is selected 
	} 
$offset = ($page - 1) * $limit; //starting number for displaying results out of DB 
	$query = "SELECT id,big,thumb,postdate, DATE_FORMAT(postdate, '%d/%m/%Y @ %T ') AS pdate FROM screenshots ORDER BY id DESC LIMIT $offset, $limit"; 
	$result = mysql_query($query); 
//This is the start of the normal results... 
$screen_id = mysql_result($result,$row,"id"); 
$screen_b = mysql_result($result,$row,"big");
$screen_t = mysql_result($result,$row,"thumb");
$screen_date = mysql_result($result,$row,"pdate");
 
	while ($row = mysql_fetch_array($result)) 
		{ 
		echo "$screen_t"; // display your results as you see fit here.
		} 
		mysql_close();
 
***CUT***

i simply want to display the 12 latest images and so on for the other pages, i only need to print the filenames correctly, can someone help me out :(

thanks alot for your time

fred

well, i have found the solution, was quite simple..i told you i am not a coder ;) hehe

echo $row['title']."<br />";

Edited 3 Years Ago by Dani: Formatting fixed

***CUT***
 
while ($row = mysql_fetch_array($result)) 
 {
 echo "<a HREF=images/ingame/".$row['big']." TARGET=_blank><img src=images/ingame/thumbs/".$row['thumb']." border=0 alt=".$row['big']."></a>&nbsp;&nbsp;"; // display your results as you see fit here.
 }
 
***CUT***

This code will display the pictures i want, but i have another problem :sad: , How do i create a nice 3x4 table to display the images ? please..


fred

I don't know PHP for anything but the following is code for one row ...

<tr>
  <td> code for picture in row 1</td>
</tr>
 
<tr>
  <td> code for picture in row 2 </td>
</tr>

So now, perhaps use code like the following? Keep in mind I'm NOT a php programmer.

echo "<table><tr>";
while ($row = mysql_fetch_array($result)) 
 {
 echo "<td><a HREF=images/ingame/".$row['big']." TARGET=_blank><img src=images/ingame/thumbs/".$row['thumb']." border=0 alt=".$row['big']."></a></td>"; // display your results as you see fit here.
if (($row % 3) == 0)
  { echo "</tr><tr>"; }
 }
</tr></table>

I doubt it was right. In fact, I just found an error ... I don't want to see if $row % 3 ... I want to see what we're on ... change that to $counter % 3, and directly above, add counter++; Then, above the while loop, add $counter=0; Sorry :)

$counter=0;
echo "<table><tr>";
while ($row = mysql_fetch_array($result)) 
 {
  echo "<td><a HREF=images/ingame/".$row['big']." TARGET=_blank><img src=images/ingame/thumbs/".$row['thumb']." border=0 alt=".$row['big']."></a></td>"; // display your results as you see fit here.
 $counter++;
 if (($counter % 3) == 0){
  echo "</tr><tr>"; 
  }
}
echo "</tr></table>";

awesome!!!!!!


thanks !!!

fred

i've tried the first script above.... but what i get ouputted is:

Pages:(3) [1]
Notice: Undefined variable: PHP_SELF in c:\inetpub\wwwroot\montblanc\berichtenAdmin.php on line 151
2
Notice: Undefined variable: PHP_SELF in c:\inetpub\wwwroot\montblanc\berichtenAdmin.php on line 151
3
Notice: Undefined variable: PHP_SELF in c:\inetpub\wwwroot\montblanc\berichtenAdmin.php on line 163
>>
Notice: Undefined variable: PHP_SELF in c:\inetpub\wwwroot\montblanc\berichtenAdmin.php on line 164
Last >>

does anyone have a clue why he tells me that php_self is undefined?

tia

Try replacing $PHP_SELF with $_SERVER

id did that... the errors were gone, BUT....
when i clicked page 2 or 3, ... there was no reaction.... the same page kept displaying.... :s

I don't know PHP for anything but the following is code for one row ...

So now, perhaps use code like the following? Keep in mind I'm NOT a php programmer.

echo "<table><tr>";
 while ($row = mysql_fetch_array($result)) 
  {
 echo "<td><a HREF=images/ingame/".$row['big']." TARGET=_blank><img src=images/ingame/thumbs/".$row['thumb']." border=0 alt=".$row['big']."></a></td>"; // display your results as you see fit here.
 if (($row % 3) == 0)
   { echo "</tr><tr>"; }
  }
 </tr></table>

Keep also in mind that you need to add "empty" cells if you want to display images in a table of 3x4.
I you have a total of 10 records, and the table has 3 rows, 4 columns, then the last row of the table has only 2 columns in it. You need to add <td></td> (or <td>&nbsp;</td>) cells to fill up the row.

I've made an example at http://quaedackers.homeip.net/testsite/table_format.php

As you can see I use 2 nested loops. 1 for the rows, and 1 for the columns. By checking if the row-object (or array) contains any data (it must NOT be false) then you can write the data in the cell. If the object equals false, then you need to write an empty cell.

echo "<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">\n"; 
 
   for($row=0; $row<$rowCount; $row++){	 // create the rows in a nice loop 
	  echo "<tr>"; 
	  for($col=0; $col<$colCount; $col++){  // create the columns in a nice nested loop 
		 echo "<td width=\"30\" align=\"center\">"; 
		 if($db_row = mysql_fetch_object($result)) 
		 // fetch the results in an object and thest if there is data. 
		 // (if there is no data, $db_row will be 'false') 
		 { 
			echo htmlentities($db_row->some_field);   // There is data, display it! 
		 } 
		 else 
		 { 
			echo "&nbsp;";	// There was no data. Write a &nbsp; to create an 'empty' cell 
		 } 
		 echo "</td>";	 // close the cell  
	  } 
	  echo "</tr>\n";	// close the row 
   } 
 
   echo "</table>\n";	// close the table

/ Patrick

LOL. seems that im a little bit late to be responding to this thread, but i will try my luck anywhy.

i have this code reading my sql and posting results, but of course i have a problem with it. if anyone can help me it would be a great help.

1. the pages do not change. it is the same page over and over again.

2. after changing this line to "4" (i have 12 entries)
$limit = "4"; //limit of archived results per page.

it displays page 1-3, but it list all of the results on each page.

how do i break apart the results so that i have 4 items per page and different results on each page.

thanks.

JB

Really nice code!!

The problem is I get the value input from users and display the results. So the value changes depending on users' search criterias.

So after FIRST page, it doesn't matter which page I click on, I've got this message:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /usr/home/wwwnnn/public_html/test/search.php on line 12

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /usr/home/wwwnnn/public_html/test/search.php on line 26
Pages: (0) << First << 1 [2] 3 4 5 >> Last >>

The $query is:

$sql = "SELECT * FROM Resident WHERE LP BETWEEN ".$_POST['minPrice']." AND ".$_POST['MaxPrice']." AND BR = ".$_POST['br']." AND BTH = ".$_POST['bth']."";

Line 12 is:

$total_results = mysql_num_rows($query);

Line 26 is:

while ($row = mysql_fetch_array($result))

Can anyone please help me out with this??? :(

There's a simple tutorial on "pagination" (results on multiple pages) on phpfreaks.com

Using LIMIT makes this thing easy I think. Though thats coming from a guy who hasn't tried it yet.

Ive done alot of stuff with 'pagination' and yes using LIMIT in your sql query is the best way to go about it. Theres basically two parts to make it work.

1. is the making the sql query match the page you're on
and
2. displaying the proper pages links, like the " << prev 1 2 3 4 next >> "

// first get the current page ( file.php?p=1 or 2 or what ever)
if(isset($_GET['p'])) $page = $_GET['p'];
else $page = 1;
// set how many entries you want per page (for example 20)
$display = 20;

// set the LIMIT for the sql query
$start = $page * $display - $display;

// then the query should look something like 
$sql = "SELECT ... FROM table WHERE ... LIMIT $start, $display";

//  The LIMIT should go at the very end of the query.

so the first page will display entries starting at 0, showing 20 entries.
page 2 will start at entry #20 and display the next 20 and ect..


The second part is showing the 'next, prev' links

// first you need a query to find how many entries there are total in the database
// I use the count function for this
$sql = "SELECT COUNT(*) AS total FROM table_name";
$total = mysql_result(mysql_query($sql),0,'total');

// then break up the total into pages
$totalpages = $total / $display;  // in this case $display = 20
// round up on pages
$totalpages = ceil($totalpages);



// if its not page 1, display a 'prev' link

if($page != 1) { 
    $prev = $page--;
    echo '<a href="'. $PHP_SELF . '?p=' . $prev . '">prev</a>';
    }

// set current page for loop
$current = 1;

// use while function to loop through each page and display link

while ($current <= $totalpages) {
    if($current == $page) echo $currentpage;
    else echo '<a href="'. $PHP_SELF . '?p=' . $currentpage . '">' . $currentpage . '</a>';
    $current++;
   }
//  if current page is not the last page, display 'next' link

if($page != $totalpages) {
    $next = $page++;
    echo '<a href="'. $PHP_SELF . '?p=' . $next . '">next</a>';
   }

And thats all there is to it. If anyone has questions about this, let me know.

Can you please tell how to use the same script in JSP for MS SQL database.

Please help, i am stuck on this problem.
Thank you.

i cant use this script any body there who can help me. I need php next page script urgently. Please provide me exact script with the following variables.

Hostname: localhost
dbname : ehdb
username: root
password:
table name: feedback


i want use this script for search box. i want search users by name and show me 5names in a table and then others are in next page.

pls help

thanks

this is a htm verson of 3x4 to but idages also im have a good scipit if you like to use it you have to download jquery-1.6.2.min from jquery website and add this code

for the scipit

<script src="jquery-1.6.2.min"></script>
<script>
function updateImage() {	
	$.get("checkimage.php?"+Math.random(), function(data) {
		$("#djimage").attr("src", data);
	});
}
setInterval("updateImage()",1000);
</script>


</body>

</html>

this is the code for the 3x4 table if you want that im hope was helpfully

<table border="1" width="12%">
	<tr>
		<td align="center"><img border="0"></td>
		<td align="center"><img border="0"></td>
		<td align="center"><img border="0"></td>
                  <td align="center"><img border="0"></td>
	</tr>
</table>

Edited 5 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post.

Resurrecting a very old thread to post random, completely unrelated code fragments is not exactly helpful.

This article has been dead for over six months. Start a new discussion instead.