If you have a "Dinamic Website" huge and has thousands of items / product you must trouble to display these items one by one in a regular, automatic and controlled.
The solution is you can use the display per page.
<-Previous 1 2 3 Next->
The contents of the page is taken from the MySql database, but that we also can determine how many items we will display the page. Interesting isn't it???
Now let's begin the PHP Tutorial :D
This is an example of a database table that I use:
CREATE TABLE `content` ( `id` int(225) NOT NULL auto_increment, `title` varchar(50) collate latin1_general_ci NOT NULL default '', `content` longtext collate latin1_general_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=5 ; |
db.php
<?php $dbhost = 'localhost';$dbusername = 'your_user'; $dbpasswd = 'your_password'; $database_name = 'your_database'; #under here, don't touch! @$connection = mysql_pconnect("$dbhost","$dbusername","$dbpasswd") or die ("Can't connect to MySQL"); @$db = mysql_select_db("$database_name", $connection) or die("Database can't be found"); ?> |
index.php
<?php /* connection to database */include 'db.php'; /* specify the table */ $table = content; $page = $_GET[page]; /* if the page default is 1 */ if(!isset($_GET['page'])){ $page = 1; } else { $page = $_GET['page']; } /* specify the number of items per page */ $max_results = 5; /* page multiply MAX number of items per page, minus the MAX number of items per page */ /* logic: 1 x 5 = 5 , 5 - 5 = 0 , so database id start from 0*/ $from = (($page * $max_results) - $max_results); /* Show from the database, LIMIT from the example above, id of 0 to 5 */ $sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT $from, $max_results "); while($row = mysql_fetch_array($sql)){ /* display result, this is depending from your table database*/ ?> <?php echo $row[2] ?><br><?php echo $row[3] ?></a><br /> <?php echo $row[1] ?> | This page read <?php echo $row[6] ?> times<br /> <?php echo $row[4]; ?> <hr> <?php }$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM $table"),0); $total_pages = ceil($total_results / $max_results); /*Build the number of hyperlink pages*/ echo "<center>Select a Page<br />"; /* Build Previous link */ if($page > 1){ $prev = ($page - 1); echo "<a href=$_SERVER[PHP_SELF]?page=$prev> <-Previous </a> "; } for($i = 1; $i <= $total_pages; $i++){ if(($page) == $i){ echo "$i "; } else { echo "<a href=$_SERVER[PHP_SELF]?page=$i>$i</a> "; } } /* Build Next link */ if($page < $total_pages){ $next = ($page + 1); echo "<a href=$_SERVER[PHP_SELF]?page=$next>Next-></a>"; } echo "</center>"; ?> |
That's all....quite easy right?
0 comments:
Post a Comment