1

我正在尝试编写一个脚本,该脚本从 MYSQL 数据库中提取特定查询,然后对结果进行分页。

我想我知道解决方案是什么,这只是我对如何实现/编写它们的知识缺乏了解的问题。

这是我部分工作的脚本:

<?php
$tstart = 0; 
$tend = 0;
//$tpage = 0; // the start page
//$tpages = 0; // number of pages
$tpagelinks = ""; // stores the output pagination
$ttotal = 0; / total number of results
$trows = 5; // number of results per page
$online = ""; // stores the results to display

$dbhost = "localhost"; 
$dbuser = "****_models"; 
$dbpass = "****";

$dbcon = @mysql_connect($dbhost,$dbuser,$dbpass) or die('Database error: ' . mysql_error());

$db = mysql_select_db('****_cammodels', $dbcon) or die('Database error: ' . mysql_error());

$query = "SELECT * FROM cbmodels WHERE gender='f' AND status='Public' AND age<='22'";

$result = mysql_query($query) or die('Query failed: ' . mysql_error() . "\nQuery: $query");

while($row = mysql_fetch_array($result))
{
  $online .= "#". $ttotal . " \n";
  $online .= $row['status'] . "/" . $row['name'] . "/" . $row['gender'] . "/" . $row['age'] . "\n";
  $online .= "<br>\n";
  $ttotal ++;
 }
 $tstart = ($tpage * $trows) - $trows;
 $tend = $tstart + $trows;
 if ($tend > $ttotal) { $tend = $ttotal; }
 $tpages = floor($ttotal / $trows);
 if ($ttotal % $trows != 0) { $tpages ++; }
 if ($tpage > $tpages) { $tpage = 1; }

 if ($tpage > 1) { $tpagelinks .= "<a class='allonlinepages_url' href='new_from_db.php?page=" . ($tpage - 1) . "'>PREVIOUS</a>\n"; }

 for ($ti = 1; $ti <= $tpages; $ti ++)
 {
 if ($tpage == $ti) { $tpagelinks .= "$ti \n"; }

    else { $tpagelinks .= "<a class='allonlinepages_url' href='new_from_db.php?page=$ti' >$ti</a>\n"; }
 }

 if ($tpage < $tpages) { $tpagelinks .= "<a class='allonlinepages_url' href='new_from_db.php?page=" . ($tpage + 1) . "' >NEXT</a>\n"; }

echo $online;
echo $tpagelinks;

mysql_close($dbcon);
?>

它所做的是显示在数据库中找到的所有结果,分页计数似乎显示正确的页数,但链接错误/不显示下一页结果。

我想我需要先查询数据库以获取分页的行数,然后计算页数,然后再进行一次查询以获取结果,也许将其存储在另一个数组中作为每页结果?或类似的东西。我已经尝试了很多次,上面的脚本是我得到的最接近的脚本,它几乎可以正常工作,我所有的其他尝试只是破坏了脚本,要么产生奇怪的结果,要么根本没有。

我从实际提要中提取数据以存储在数据库中的脚本本身标记在线和离线工作正常,所以我没有包含它,因为它是一个单独的脚本。

提前感谢您对伙计们的任何帮助。

编辑 删除了所有无效的代码 RE:评论。

4

2 回答 2

12

是的,首先您需要找出记录的总数。然后再次运行查询,这次在查询的末尾加上一个 LIMIT。例如 LIMIT 0, 10。此示例返回从记录 0(第一条记录)开始的 10 个结果。如果您使用变量动态设置限制结果的第一条记录,则可以让它随每一页更新。对于每一页,您都可以计算出您想要的起始记录。例如,$offset= $recordsperpage * 页码。

我不确定你的变量到底是什么,所以我不会玩弄你的脚本。这是我在一个我知道可行的项目中使用的示例。示例脚本:

//Use mysqli object instead of mysql_xxx, better security
$db3= new mysqli($hostname, $username, $password, $dbname);

     //how many records I want per page
    $perPage= 9;

    //I'm passing the startrecording as a Get variable in the page links 
    if($_GET['startingrecord']){
        $startingRecord=trim($_GET['startingrecord']);
    }

    //but if there is no get variable, start at record zero
    else {
        $startingRecord=0;
    }


    //prepare your query
    $stmt3 = $db3->prepare("SELECT DISTINCT file, category, P.productID, price, title, price * (1- sale) FROM Products AS P INNER JOIN OrderProducts AS OP ON P.productID NOT IN (Select productID from OrderProducts) Left JOIN Sale AS S on P.productID= S.ProductID ORDER BY productID DESC");

    // You can bind parameters if necessary, but it's not here

    //execute the query and store the result
    $stmt3 -> execute();
    $stmt3->store_result();

    //determine the number of total rows
    $numberRows= $stmt3->num_rows;

    //close the db
    $db3 -> close;

   //Reopen with limits this time.
    $db3= new mysqli($hostname, $username, $password, $dbname);


    $stmt3 = $db3->prepare("SELECT DISTINCT file, category, P.productID, price, title, price * (1- sale) FROM Products AS P INNER JOIN OrderProducts AS OP ON P.productID NOT IN (Select productID from OrderProducts) Left JOIN Sale AS S on P.productID= S.ProductID ORDER BY productID DESC LIMIT ?, ?");
    // bind the startingrecord from the get variable and the perpage variable.
     stmt3->bind_param("ii", $startingRecord, $perPage);

    //you use ceiling to make sure if that if there's a remainder, you have an extra page for the stray results
    $pages= ceil($numberRows/ $perPage);

   //This is me generating the page links
    for ($i=1; $i<= $pages; $i++) {
        if ($i==1){
            $start=0;
        }
        else{
            $start= ($i-1) * ($perPage);
        }
        echo "<a href='#' onclick='gallery(\"startingrecord=".$start."\")'>".$i." </a>";
    }   

    $stmt3 -> execute();
    $stmt3->store_result();
    $stmt3->bind_result($file, $category2, $productID, $price, $title2, $sale); 

    while($stmt3->fetch()){ 
    // do whatever you want to your result

     })
于 2013-06-18T01:43:26.183 回答
-1
<style>
ul.pagination {
font-family: "Arial", "Helvetica", sans-serif;
font-size: 13px;
height: 100%;
list-style-type: none;
margin: 20px 0;
overflow: hidden;
padding: 0; }
ul.pagination li.details {
background-color: white;
border-color: #C8D5E0;
border-image: none;
border-style: solid;
border-width: 1px 1px 2px;
color: #1E598E;
font-weight: bold;
padding: 8px 10px;
text-decoration: none; }
ul.pagination li.dot {
padding: 3px 0; }
ul.pagination li {
float: left;
list-style-type: none;
margin: 0 3px 0 0; }
ul.pagination li:first-child {
margin-left: 0; }
ul.pagination li a {
color: black;
display: block;
padding: 7px 10px;
text-decoration: none; }
ul.pagination li a img {
border: medium none; }
ul.pagination li a.current {
background-color: white;
border-radius: 0 0 0 0;
color: #333333; }
ul.pagination li a.current:hover {
background-color: white; }
ul.pagination li a:hover {
background-color: #C8D5E0; }
ul.pagination li a {
background-color: #F6F6F6;
border-color: #C8D5E0;
border-image: none;
border-style: solid;
border-width: 1px 1px 2px;
color: #1E598E;
display: block;
font-weight: bold;
padding: 8px 10px;
text-decoration: none; }
</style>
<?php
/******************************************pagination*****function*****************************************/
function pagination($per_page = 10, $page = 1, $url = '', $total){ 
$adjacents = "2";
$page = ($page == 0 ? 1 : $page); 
$start = ($page - 1) * $per_page; 
$prev = $page - 1; 
$next = $page + 1;
$lastpage = ceil($total/$per_page);
$lpm1 = $lastpage - 1;
$pagination = "";
if($lastpage > 1)
{ 
$pagination .= "<ul class='pagination'>";
$pagination .= "<li class='details'>Page $page of $lastpage</li>";
if ($lastpage < 7 + ($adjacents * 2))
{ 
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<li><a class='current'>$counter</a></li>";
else
$pagination.= "<li><a href='{$url}$counter'>$counter</a></li>"; 
}
}
elseif($lastpage > 5 + ($adjacents * 2))
{
if($page < 1 + ($adjacents * 2)) 
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= "<li><a class='current'>$counter</a></li>";
else
$pagination.= "<li><a href='{$url}$counter'>$counter</a></li>"; 
}
$pagination.= "<li class='dot'>...</li>";
$pagination.= "<li><a href='{$url}$lpm1'>$lpm1</a></li>";
$pagination.= "<li><a href='{$url}$lastpage'>$lastpage</a></li>"; 
}
elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$pagination.= "<li><a href='{$url}1'>1</a></li>";
$pagination.= "<li><a href='{$url}2'>2</a></li>";
$pagination.= "<li class='dot'>...</li>";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= "<li><a class='current'>$counter</a></li>";
else
$pagination.= "<li><a href='{$url}$counter'>$counter</a></li>"; 
}
$pagination.= "<li class='dot'>..</li>";
$pagination.= "<li><a href='{$url}$lpm1'>$lpm1</a></li>";
$pagination.= "<li><a href='{$url}$lastpage'>$lastpage</a></li>"; 
}
else
{
$pagination.= "<li><a href='{$url}1'>1</a></li>";
$pagination.= "<li><a href='{$url}2'>2</a></li>";
$pagination.= "<li class='dot'>..</li>";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<li><a class='current'>$counter</a></li>";
else
$pagination.= "<li><a href='{$url}$counter'>$counter</a></li>"; 
}
}
}

if ($page < $counter - 1){
$pagination.= "<li><a href='{$url}$next'>Next</a></li>";
// $pagination.= "<li><a href='{$url}$lastpage'>Last</a></li>";
}else{
//$pagination.= "<li><a class='current'>Next</a></li>";
// $pagination.= "<li><a class='current'>Last</a></li>";
}
$pagination.= "</ul>\n"; 
} 
return $pagination;
} 
/****************************************////**pagination*****function*****************************************/
?>



<!---------------------------pagination------------------------------------------------->
<?php 
//error_reporting(0);
$con = mysqli_connect("localhost","root","","accounts");
$page=1;//Default page
$limit=2;//Records per page
$start=0;//starts displaying records from 0
if(isset($_GET['page']) && $_GET['page']!=''){
$page=$_GET['page'];
}
$start=($page-1)*$limit;
?>


<!---------------------------pagination-------end------------------------------------------>

<table width="100%" >
<tr>
<td>

<?php

$query = mysqli_query($con,"select * from receipts");
$rows=mysqli_num_rows($query);
//newly registerd on top
$query=mysqli_query($con,"select * from receipts order by r_id ASC LIMIT $start, $limit");


if(mysqli_num_rows($query)>0){

while($row = mysqli_fetch_array($query,1)){
?>
  <table cellpadding="3" cellspacing="3" border="1px #f8f8f8" width="100%" style="background-color:#FFFFFF;border:1px solid #e8e8e8">  
  <tr>
  <td id="class1">Name</td>
  <td id="class2"><?php echo $row['party_name'] ;?></td>
  </tr>
    <tr><td id="class1">Roll No</td>
    <td width="700px" id="class2"><?php echo $row['receipt_no']; ?></td>
    </tr>
    <tr>
    <td id="class1" width="170px">Date</td>
    <td id="class2"><?php echo $row['date1']; ?></td>
    </tr>
    </table>

<?php
}}

?>
</td>
</tr>
</table>

<?php
if(empty($_GET['id']))
{
    $id = 1;
}
if(isset($_GET['id'])){
    $id = $_GET['id'];
}
echo '</table><table>';
echo "<tr><td>";

echo pagination($limit,$page,'try.php?id='.$id.'&page=',$rows); //call function to show pagination

echo "</td></tr>";
echo "</table>";
?>
</div>
于 2014-06-25T16:44:20.120 回答