PHP simple : PHP tutorial, MySQL tutorial
PHP Tutorial - Free PHP Script

Home | Tutorials | Php vs Node.Js | Web Tools

Page Navigator


Tutorials > Page Navigator

Most of PHP scripts as guestbook, webboard, online catalog, etc. have many records in database. So, not good idea to show them in one page. This tutorial will show you how to create the page navigator and apply it.

This tutorial require 1 PHP file and 1 table of mySQL database.

  1. page.php
  2. Database "tutorial" and table "name_list" with 2 fields: id(auto_increment), name(varchar, 50) and put some records about 20 - 30 records into this table. (directly by phpMyAdmin)


page.php

This page will show the records with page navigator on the top.

page navigator

Source Code
<?
// Connect database
mysql_connect("localhost","","");
mysql_select_db("tutorial");

$table="name_list"; // Set database table name.
$pagesize=5; // Set number of records to view on this page.

// Get only one column(id) from table.
$result=mysql_query("select id from $table;");
// Count the total of records by mysql_num_rows() function and set it to $totalrecord.
$totalrecord=mysql_num_rows($result);

// How many pages will be. Set it to $totalpage.
$totalpage=(int)($totalrecord/$pagesize);
if(($totalrecord%$pagesize)!=0){
$totalpage+=1;
}

/* If this page get $pageid variable, set $pageid and starting record as $start.
If not, $pageid set to 1 and $start set at 0 (first record in table) */

if(isset($pageid)){
$start=$pagesize*($pageid-1);
}
else{
$pageid=1;
$start=0;
}

// Select records from table with limit statement and put them to $result.
$result=mysql_query("select * from $table order by id asc limit $start, $pagesize;");
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<?
// This is the Page Navigator.
for ($i=1; $i<=$totalpage; $i++){
if ($i==$pageid){
echo "<b>".$i."</b> | ";
}
else{
echo '<a href='.$PHP_SELF.'?pageid='.$i.'><b>' .$i.'</b></a> | ';
}
}
?>

<table border="1">
<tr>
<td>No.</td>
<td>Name</td>
</tr>
<?
// Show records made by while loop on table rows (<tr> tag).
while($row=mysql_fetch_assoc($result)){
?>

<tr>
<td><? echo $row['id']; ?></td>
<td><? echo $row['name']; ?></td>
</tr>
<?
// End while loop.
}

// Close database connection.
mysql_close();
?>

</table>
</body>
</html>

Advertise
Put Ebay RSS Feeds onto your website
SEO Elite Software
Domain Dashboard CPanel & Seo Manager
Work at Home Ideas and Opportunities
Introduction & Get Start
Using Form
PHP
PHP Tags
PHP Variables
PHP Control Structures
MySQL
Create Database & Table
Database Connection
Insert Record
Select Record
Update Record
Delete Record

PHPsimple.net
info@phpsimple.net