如何使用PHP创建分页系统?

时间:2014-02-24 04:57:58

标签: php design-patterns pagination

我有一个PHP页面,一次显示我的MySQL表数据四行。例如,如果有九行,则第一页将是http://webste.ca/usedunits.php?page=1并显示前四行。第二页将是http://webste.ca/usedunits.php?page=2并显示第五行到第八行,第三页将是http://webste.ca/usedunits.php?page=3并显示第九行。

我正在尝试制作一个显示为箭头的链接,如果用户在http://webste.ca/usedunits.php?page=2上,则会将其发送到http://webste.ca/usedunits.php?page=1。如果它们位于第2页,则会有指向第3页的链接,依此类推。

我也试图创建一个显示为快进按钮的链接,将用户发送到最后一页。我的问题实际上是在制作这个功能。

这是我的完整PHP页面代码:

<?php 
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; }; 
$dbhost = 'dnam';
$dbuser = 'kabm';
$dbpass = 'Kazer';
$dbname = 'kam';
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $connection )
{
  die('Could not connect: ' . mysqli_error());
}
$start_from = ($page-1) * 4; 
$sql = "SELECT * FROM `used_trailers` ORDER BY `orderid` ASC LIMIT $start_from,4";
$rs_result = mysqli_query ($connection, $sql); 
echo mysqli_error( $connection );
?>
<!doctype html>
<!--[if lt IE 7]> <html class="ie6 oldie"> <![endif]-->
<!--[if IE 7]>    <html class="ie7 oldie"> <![endif]-->
<!--[if IE 8]>    <html class="ie8 oldie"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="">
<!--<![endif]-->
<head>
<meta name="author" content="Kelsey Nealon(Kelseynealon@gmail.com), Contract Web Developer" />
<meta name="description" content="GBM Trailer Service Ltd. Calgary-based, proudly serving the tanker and bulk goods transportation industry for over 25 years." />
<meta name="keywords" content="Tanker, Barrel, Parts, Betts, Camloc, Scully, Lubecore, Dixon, GBM, Flotech" />
<title>GBM Trailer Service Ltd. ::: Service</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/mobilemenu.css"/>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="responsiveused.css" rel="stylesheet" type="text/css">
<link href="perfect-scrollbar.css" rel="stylesheet" type="text/css" />
<!-- 
To learn more about the conditional comments around the html tags at the top of the file:
paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/

Do the following if you're using your customized build of modernizr (http://www.modernizr.com/):
* insert the link to your js here
* remove the link below to the html5shiv
* add the "no-js" class to the html tags at the top
* you can also remove the link to respond.min.js if you included the MQ Polyfill in your modernizr build 
-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- jQuery library (served from Google) -->
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- include Cycle2 -->
<script src="jquery.mousewheel.js"></script>
<script src="perfect-scrollbar.js"></script>
<script src="jquery.cycle2.min.js"></script>

<script>
        $(document).ready(function(){
            $(".nav-button").click(function () {
            $(".nav-button,.primary-nav").toggleClass("open");
            });    
        });
    </script>

    <script>
      jQuery(document).ready(function ($) {
        "use strict";
        $('.Default').perfectScrollbar();
      });
    </script>

<script src="respond.min.js"></script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-45342007-3', 'gbmtrailer.ca');
  ga('send', 'pageview');

</script>
</head>
<body bgcolor="#102540">
<div class="gridContainer clearfix">
  <div id="div1" class="fluid">
    <div id="navcontain"></div>

  <div id="wrapper">
    <div id="cover"></div>
  <div id="mainnaviphone">
    <a href="../index.html"><img id="logo" src="images/gbmlogo.jpg" alt="G.B.M. Trailer Service LTD. Logo" title="G.B.M. Trailer Service LTD. Logo"/></a>
    <img src="images/newunitsbutton.png" alt="New Units Button" title="New Units Button" id="buto1">
  <img src="images/usedunitsbutton.png" alt="Used Units Button" title="Used Units Button" id="buto2">
  <a href="../index.html"><img src="images/homebutton.png" alt="home" title="Home" id="homebuto"/></a>
  <a href="#"><img src="images/previousbutton.png" alt="previous" title="Previous" id="prevbuto"/></a>
  <a href="#"><img src="images/nextbutton.png" alt="next" title="Next" id="nextbuto"/></a>
</div>

<div id="background2">
<div id="textcontrol">

<?php 
while ($row = mysqli_fetch_assoc($rs_result)) { 
?> 
<div id='used1'>
<div id='rigtitle' class="contentHolder Default">
<? echo $row["title"]; ?>
</div>
<table class="infotabe1"><tr><td class="desctde">Description: </td><td rowspan="2" id="content_1" class="infotde contentHolder Default"><? echo $row["description"]; ?></td></tr></table>
<table class="infotabe"><tr><td class="desctd">Make: </td><td id="content_1" class="infotd contentHolder Default"><? echo $row["make"]; ?></td></tr></table>
<table class="infotabe"><tr><td class="desctd">Model: </td><td id="content_1" class="infotd contentHolder Default"><? echo $row["model"]; ?></td></tr></table>
<table class="infotabe"><tr><td class="desctd">Year: </td><td id="content_1" class="infotd contentHolder Default"><? echo $row["year"]; ?></td></tr></table>
<table class="infotabe"><tr><td class="desctd">Price: </td><td id="content_1" class="infotd contentHolder Default"><? echo $row["price"]; ?></td></tr></table>

<!-- Unit Picture -->
<img src='images/<? echo $row["photo"]; ?>' id='mainimage'>
<a href='#'><img src='images/picturesandspecsbutton.png' alt='Pictures and Specs' title='Pictures and Specs' id='picsandspecsbuto'></a>
</div>
<?php 
}; 
?>
</div>
<div id="description" class="resize">
  <p><u>Click</u> or call for more information or enquiries.</p>
</div>
<div id="bottomquote">
  Your Certified Tanker Trailer Specialist
</div>
<div id="bottomcontactinfo">
  <em>Phone <a style="color:white; text-decoration:none;" href="tel:1-4032799717">403 279 9717</a> or <a style="color:white; text-decoration:none;" href="tel:1-888-426-9717">1 888 426 9717</a> 9300 Endeavor Dr. SE, Calgary Alberta, T3S 0A1<br /><a style="color:white; text-decoration:none;" href="mailto:info@gbmtrailer.ca">info@gbmtrailer.ca</a>
</div>

<img src="images/visamastercardlogos.gif" id="visamastercardlogos" alt="Visa and Mastercard Logo" title="Visa and Mastercard Logo">

<a href="#"><img id="mycart" src="images/mycart.gif" alt="My Cart" title="My Cart"></a>
</div>
</div>
</div>
</div>

<script>
<!--
var autoSizeText;
autoSizeText = function() {
  var el, elements, _i, _len, _results;
  elements = $('.resize');
  console.log(elements);
  if (elements.length < 0) {
    return;
  }
  _results = [];
  for (_i = 0, _len = elements.length; _i < _len; _i++) {
    el = elements[_i];
    _results.push((function(el) {
      var resizeText, _results1;
      resizeText = function() {
        var elNewFontSize;
        elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';
        return $(el).css('font-size', elNewFontSize);
      };
      _results1 = [];
      while (el.scrollHeight > el.offsetHeight) {
        _results1.push(resizeText());
      }
      return _results1;
    })(el));
  }
  return _results;
};

autoSizeText(); // here is where we call the function.
</script>
</body>
</html>
<?php 
$sql = "SELECT COUNT(`orderid`) FROM `used_trailers`";
$rs_result = mysqli_query($connection, $sql); 
$row = mysqli_fetch_row($rs_result); 
$total_records = $row[0]; 
$total_pages = ceil($total_records / 4); 

$sqlef = 'SELECT * FROM `used_trailers`';
$rs_resultt = mysqli_query($connection, $sqlef); 
$rowcount = mysqli_num_rows($rs_resultt);

$record_start = $start_from + 1;
$record_end   = $record_start + 3;

// Remember to check against the max record
if ($record_end > $total_records) {
   $record_end = $total_records;
}

    echo "Showing ".$record_start." - ".$record_end." of ".$rowcount." results ";
    echo "asd<a href='usedunits.php?page=".$i."'>".$i."</a>";
for ($i=1; $i<=$total_pages; $i++) { 
            echo "<a href='usedunits.php?page=".$i."'>".$i."</a> "; 
}; 
?>

1 个答案:

答案 0 :(得分:1)

如果您想要链接到最后一页,您需要知道最后一页的内容。

这样做的方法是对您的数据库进行额外的查询,询问与标准匹配的项目总数,以及您和您的步骤(即每页的项目数)计算页数。

在您的示例中,查询将是

SELECT count(*) FROM `used_trailers`

P.S。假设您将该查询的结果放在$count变量中,则最后一页(从1开始计算)将为ceil($count / 4)$count == 0的一个角点),4为数字您根据代码在每个页面上显示的项目。