Thursday, March 26, 2009

Pagination in PHP

Pagination in PHP




Step One

  1. Connect to MySQL database.
For those who are new to PHP & MySQL and do not know how to establish connection with MySQL, may use the following config.php.file code.

//Host name

$host='localhost';

//User name

$user='root';

//Password

$pass='';

//Database name

$db='mydb';

//Establishing database connection

mysql_connect($host,$user,$pass);

//Select database

mysql_select_db($db) or die ("Database Connection Failed") ;

?>


Step Two
  1. Set Variables:
  2. Set table name you want to use (Table must contain an auto increment field named “Id”).
  3. Set the column name you want to show.
  4. Set number of rows per page (default is 5 rows/page).
After configure variables as defined above, simply run the script and enjoy {:-Þ

//Include config file

includes('config.php');

//Table name

$myTable='Mytable';

//Column Name

$columnName='Columnname';

//How many rows to show per pg

$rowsperpg=5;

//by default we show first pg

$pgnum=1;

//if $_GET['page'] defined, use it as first page number

if(isset($_GET['page']))

{

$pgnum=$_GET['page'];

}

//counting the offset

$offset=($pgnum-1)*$rowsperpg;

$test="SELECT * FROM '".$myTable."' LIMIT $offset,$rowsperpg";

$run=mysql_query($test) or die('selection fail');

//print

$count=mysql_num_rows($run);

if($count > 0)

{

while($res=mysql_fetch_assoc($run))

{

echo '

';

echo '

';

echo '

Event: '.$res[$columnName].'
';

echo '
'
;

}

//how many rows we have in db

$query="SELECT COUNT(Id) as numrows FROM '".$myTable."' ";

$res=mysql_query($query) or die('Error Query failed');

$row=mysql_fetch_assoc($res);

$numrows=$row['numrows'];

//how many pg we have when using paging?

$maxpg=ceil($numrows/$rowsperpg);

// print the link

$self=$_SERVER['PHP_SELF'];

$nav='';

for($page=1;$page<=$maxpg;$page++)

{

if($page==$pgnum)

{

$nav.="$page";

}

else

{

$nav.="$self?page=$page\">$page";

}

}

if($pgnum>1)

{

$page=$pgnum-1;

$prev="$self?page=$page\">[Prev]";

$first="$self?page=1\">[First Page]";

}

else

{

$prev=' ';

$first=' ';

}

if($pgnum<$maxpg)

{

$page=$pgnum+1;

$next="$self?page=$page\">[Next]";

$last="$self?page=$maxpg\">[Last Page]";

}

else

{

$next=' ';

$last=' ';

}

echo '

'.$first.' '.$prev.' '.'page'. $pgnum.' '.' of'.' '.$maxpg.' '.$next.' '.$last.'
';

}

if($count <= 0)

{

?>

<div style="color: #FF3300" align="center">

<p><h5>No Record Availableh5>p>

div>

}

?>

No comments: