Introduction:
This tutorial will show you how to paginate content from a database in the simplest, most effective way in two simple steps.
Step 1 - The Database:
The first step is to create the table to hold the data. Execute the following code.
DROP TABLE IF EXISTS `news`;
CREATE TABLE `news` (
`id` int(255) NOT NULL auto_increment,
`title` text NULL default '',
`story` text NULL,
`author` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`),
) ENGINE=MyISAM;
Step 2 - The Script:
[php]<?php
$host = "your_host"; //your sql host, usually 'localhost'
$user = "username"; //username to connect to database
$pass = "password"; //password to connect to database
$db = "your_database"; //the name of the database
mysql_connect($host,$user,$pass) or die("ERROR:".mysql_error());
mysql_select_db($db) or die("ERROR DB:".mysql_error());
$max = 25; //amount of articles per page. change to what to want
$p = $_GET['p'];
if(empty($p))
{
$p = 1;
}
$limits = ($p - 1) * $max;
//view the news article!
if(isset($_GET['act']) && $_GET['act'] == "view")
{
$id = $_GET['id'];
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
while($r = mysql_fetch_array($sql))
{
$title = $r['title'];
$story = $r['story'];
$author = $r['author'];
echo "<div><p>$title</p><p>$author</p><p>$story</p></div>";
}
}else{
//view all the news articles in rows
$sql = mysql_query("SELECT * FROM news LIMIT ".$limits.",$max") or die(mysql_error());
//the total rows in the table
$totalres = mysql_result(mysql_query("SELECT COUNT(id) AS tot FROM news"),0);
//the total number of pages (calculated result), math stuff...
$totalpages = ceil($totalres / $max);
//the table
echo "<table><tr><td>Title</td><td>Author</td></tr><tr>";
while($r = mysql_fetch_array($sql))
{
$id = $r['id'];
$title = $r['title'];
$author = $r['author'];
echo "<td><a href='news.php?act=view&id=$id'>$title</a></td><td>$author</td>";
}
//close up the table
echo "</tr></table>";
for($i = 1; $i <= $totalpages; $i++){
//this is the pagination link
echo "<a href='news.php?p=$i'>$i</a>|";
}
}
?>[/php]
Conclusion:
Remember to plug in your own details for the database part up top. Thats all you should really need to edit, and probably the max results also.