【问题标题】:MYSQL query with PHP pagination带有 PHP 分页的 MYSQL 查询
【发布时间】:2015-04-16 19:34:27
【问题描述】:

我正在尝试编写一个脚本,从 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: Comments。

【问题讨论】:

    标签: php mysql pagination


    【解决方案1】:

    是的,首先您需要找出记录的总数。然后再次运行查询,这次在查询的末尾加上一个 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
    
         })
    

    【讨论】:

    • 好的,我已经实现了这些更改,现在我得到的是列表中正确数量的结果,但分页中只有 2 页但是当您单击第二页时,它确实显示下一组结果...我在计数中回显了 var,但它只显示 1 个结果?
    • 我将修改后的脚本添加到原始帖子中,以防万一您没有注意到它,谢谢...(我想我可以包含测试页面的 url,但它是托管在成人上的域,所以我认为这里不能接受)
    • 小心一个接一个的错误。我已经写过好几次分页代码了,有几个地方你需要四舍五入或添加一个没有立即意义的地方。
    • 目前没有任何意义大声笑,我改变了一些计算并没有取得任何进展......除了确认它只从数据库中提取 10 行,所以我将 var age
    • 我将向您展示我几天前编写的分页脚本,您可以将其用作基础。我会尽快发布它。现在我更详细地查看了您的代码,我注意到您正在使用已弃用的对象...
    【解决方案2】:
    <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>
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多