Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中的分页(分页注释)_Php_Pagination - Fatal编程技术网

PHP中的分页(分页注释)

PHP中的分页(分页注释),php,pagination,Php,Pagination,我看了关于PHP分页的视频教程。作者在他的教程中使用了第四版PHP。现在,我想为我的评论页面分页。我使用了在教程中学习的代码。代码如下: $limit = 10; $page = $_GET['page']; if(($page='') or !is_numeric($page)){ $page = 1; } $total_posts = mysql_num_rows(mysql_query("SELECT * FROM comments")); $total_pages = ceil

我看了关于PHP分页的视频教程。作者在他的教程中使用了第四版PHP。现在,我想为我的评论页面分页。我使用了在教程中学习的代码。代码如下:

$limit = 10;
$page = $_GET['page'];
if(($page='') or !is_numeric($page)){
    $page = 1;
}

$total_posts = mysql_num_rows(mysql_query("SELECT * FROM comments"));
$total_pages = ceil($total_posts / $limit);
$start = ($page-1)*$limit;

$query = mysql_query("SELECT * FROM comments ORDER BY likes DESC LIMIT $start,$limit");
while($write = mysql_fetch_array($query)){
    $id      = $write['id'];
    $comment = $write['comment'];
    $likes   = $write['likes'];

    echo $id . ' ' . $comment . ' ' . $likes . '<br>' ;
}
但是,当我分页页面时,页面的内容不会改变。例如,comments.php?page=1中的注释与comments.php?page=2中的注释相同

它是否取决于PHP的版本?因为,这段代码在视频教程中起作用 请帮我找出问题所在。

或与其他方法不同||

试着改用| |

无论发生什么情况,您都在每个页面加载上设置$page=。所以总是第一页

if(($page='') or !is_numeric($page)){ //!!!ahhh
    $page   = 1;
}
改为:

if(($page == '') || !is_numeric($page)){
   $page = 1;
}

即使代码可能已经过时,为什么它不适用于您是$page if-on-top-see

接下来,查询所有注释以获得注释数,这是一个混乱。分页的好处是不查询所有注释,而只查询部分注释。让我们简化您的示例:

// configuration
$limit = 10; # comments per page

// input
$page = isset($_GET['page']) ? $_GET['page'] : 1; # page to display
$page = max(1, $page); # minimum value is 1

// get number of comments
list($total_posts) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM comments"));
$total_pages = min(1, ceil($total_posts/$limit)); # even with no commment, total pages is 1
$page = min($page, $total_pages); # the maximum page number is total pages

// get this page's comments    
$start = ($page-1)*$limit; # row offset
$query = mysql_query("SELECT * FROM comments ORDER BY likes DESC LIMIT $start, $limit");

// output    
while ($write = mysql_fetch_array($query))
{
    $id      = $write['id'];
    $comment = $write['comment'];
    $likes   = $write['likes'];

    echo $id . ' ' . $comment . ' ' . $likes . '<br>' ;    
}

通常,这是一个很好的实践

if ( "" == $page )
而不是

if( $page == "" )
很明显,我遇到了这样的输入错误,您最终会看到一个错误,而不是将变量意外地分配给一个难以捕获/调试的字符串

试试这个:

<?php
/*
    Place code to connect to your DB here.
*/
include('config.php');  // include your code to connect to DB.

$tbl_name="";       //your table name
// How many adjacent pages should be shown on each side?
$adjacents = 3;

/* 
   First get total number of rows in data table. 
   If you have a WHERE clause in your query, make sure you mirror it here.
*/
$query = "SELECT COUNT(*) as num FROM $tbl_name";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

/* Setup vars for query. */
$targetpage = "filename.php";   //your file name  (the name of this file)
$limit = 2;                                 //how many items to show per page
$page = $_GET['page'];
if($page) 
    $start = ($page - 1) * $limit;          //first item to display on this page
else
    $start = 0;                             //if no page var is given, set start to 0

/* Get data. */
$sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);

/* Setup page vars for display. */
if ($page == 0) $page = 1;                  //if no page var is given, default to 1.
$prev = $page - 1;                          //previous page is page - 1
$next = $page + 1;                          //next page is page + 1
$lastpage = ceil($total_pages/$limit);      //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1;                      //last page minus 1

/* 
    Now we apply our rules and draw the pagination object. 
    We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{   
    $pagination .= "<div class=\"pagination\">";
    //previous button
    if ($page > 1) 
        $pagination.= "<a href=\"$targetpage?page=$prev\">� previous</a>";
    else
        $pagination.= "<span class=\"disabled\">� previous</span>"; 

    //pages 
    if ($lastpage < 7 + ($adjacents * 2))   //not enough pages to bother breaking it up
    {   
        for ($counter = 1; $counter <= $lastpage; $counter++)
        {
            if ($counter == $page)
                $pagination.= "<span class=\"current\">$counter</span>";
            else
                $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
        }
    }
    elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
    {
        //close to beginning; only hide later pages
        if($page < 1 + ($adjacents * 2))        
        {
            for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<span class=\"current\">$counter</span>";
                else
                    $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
            }
            $pagination.= "...";
            $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
            $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";       
        }
        //in middle; hide some front and some back
        elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
        {
            $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
            $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
            $pagination.= "...";
            for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<span class=\"current\">$counter</span>";
                else
                    $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
            }
            $pagination.= "...";
            $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
            $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";       
        }
        //close to end; only hide early pages
        else
        {
            $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
            $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
            $pagination.= "...";
            for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "<span class=\"current\">$counter</span>";
                else
                    $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";                 
            }
        }
    }

    //next button
    if ($page < $counter - 1) 
        $pagination.= "<a href=\"$targetpage?page=$next\">next �</a>";
    else
        $pagination.= "<span class=\"disabled\">next �</span>";
    $pagination.= "</div>\n";       
}

?>


<?php
    while($row = mysql_fetch_array($result))
    {

    // Your while loop here

    }
?>
请使用这段代码这是简单的PHP和MySQL与CSS,而不是Jquery或任何js


哈是的,我正要说出拼写错误:$page=而不是DOUBLE==我用了| |而不是'or'。但问题并没有解决:@John your welcome^ u^。请记住在可能的情况下选择一个可接受的答案:-DThanx以获取您的建议。我将使用它。简单php分页脚本下载自:
<?php
// You have to put your mysql connection data and alter the SQL queries(both queries)
mysql_connect("DB_Host_Here","DB_Username_Here","DB_Password_Here") or die (mysql_error());
mysql_select_db("DB_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Adam's Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
} 
//This is where we set how many database items to show on each page 
$itemsPerPage = 10; 
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
} 
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage; 
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit"); 
//////////////////////////////// END Adam's Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Adam's Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    } 
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    } 
}
///////////////////////////////////// END Adam's Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){ 

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Adam's Pagination</title>
<style type="text/css">
<!--
.pagNumActive {
    color: #000;
    border:#060 1px solid; background-color: #D2FFD2; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:link {
    color: #000;
    text-decoration: none;
    border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:visited {
    color: #000;
    text-decoration: none;
    border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:hover {
    color: #000;
    text-decoration: none;
    border:#060 1px solid; background-color: #D2FFD2; padding-left:3px; padding-right:3px;
}
.paginationNumbers a:active {
    color: #000;
    text-decoration: none;
    border:#999 1px solid; background-color:#F0F0F0; padding-left:3px; padding-right:3px;
}
-->
</style>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div> 
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html>
Try this. Its perfect and working very fine.

<?php
$cur_rre_nt_page=isset($_GET['p'])?$_GET['p']:1;
$records_per_page=(isset($manual_limit)&&$manual_limit>0)?$manual_limit:5;// set limit in $manual_limit before including this file if you want to add manual limit
$page_limit=5; // Links to be shown on a page this must be odd number like and greater than 1 like 1,3,5,7,9.. 
$total_pages=ceil($num_totrec/$records_per_page);
$var_limit=" LIMIT ".(($cur_rre_nt_page-1)*$records_per_page).",$records_per_page";
$var_file_url=$current_file_front_end;
if($total_pages<=1)
{
    $page_links='';
}
else
{
    if($cur_rre_nt_page<=ceil($page_limit/2))
    {
        $page_link="<a tabindex=\"0\" href=\"$var_file_url?p=1\" class=\"first paginate_button\" id=\"DataTables_Table_0_first\">First</a>";
        $page_link.=$cur_rre_nt_page>1?"<a tabindex=\"0\" href=\"$var_file_url?p=".($cur_rre_nt_page-1)."$str_url\" class=\"first paginate_button\" id=\"DataTables_Table_0_first\">Previous</a>":'';
        for($i=1;$i<=$page_limit;$i++)
        {
            if($i<=$total_pages)
            {
                if($i==$cur_rre_nt_page)
                {
                    $page_link.="<span class=\"paginate_active\">$i</span>";
                }
                else
                {
                    $page_link.="<a href=\"$var_file_url?p=$i$str_url\" class=\"paginate_button\" id=\"DataTables_Table_$i\">$i</a>";
                }
                if($i==$page_limit && $i<$total_pages)
                {
                    $page_link.='...';
                }
            }
        }
        $page_link.=($cur_rre_nt_page<$total_pages)?"<a tabindex=\"0\" href=\"$var_file_url?p=".($cur_rre_nt_page+1)."$str_url\" class=\"first paginate_button\" id=\"DataTables_Table_0_nextt\">Next</a>":'';
        $page_link.="<a tabindex=\"0\" href=\"$var_file_url?p=$total_pages$str_url\" class=\"last paginate_button\" id=\"DataTables_Table_0_last\">Last</a>";
    }
    elseif($cur_rre_nt_page<=($total_pages-ceil($page_limit/2)))
    {
        $page_link="<a tabindex=\"0\" href=\"$var_file_url?p=1\" class=\"first paginate_button\" id=\"DataTables_Table_0_first\">First</a>";
        $page_link.="<a tabindex=\"0\" href=\"$var_file_url?p=".($cur_rre_nt_page-1)."$str_url\" class=\"first paginate_button\" id=\"DataTables_Table_0_first\">Previous</a>...";
        for($i=$cur_rre_nt_page-floor($page_limit/2);$i<=$cur_rre_nt_page+floor($page_limit/2);$i++)
        {
            if($i==$cur_rre_nt_page)
            {
                $page_link.="<span class=\"paginate_active\">$i</span>";
            }
            else
            {
                $page_link.="<a href=\"$var_file_url?p=$i$str_url\" class=\"paginate_button\" id=\"DataTables_Table_$i\">$i</a>";
            }
            if($i==$cur_rre_nt_page+floor($page_limit/2) && $i<$total_pages)
            {
                $page_link.="...";
            }

        }
        $page_link.="<a tabindex=\"0\" href=\"$var_file_url?p=".($cur_rre_nt_page+1)."$str_url\" class=\"first paginate_button\" id=\"DataTables_Table_0_nextt\">Next</a>";
        $page_link.="<a tabindex=\"0\" href=\"$var_file_url?p=$total_pages$str_url\" class=\"last paginate_button\" id=\"DataTables_Table_0_last\">Last</a>";
    }
    else
    {
        $page_link="<a tabindex=\"0\" href=\"$var_file_url?p=1\" class=\"first paginate_button\" id=\"DataTables_Table_0_first\">First</a>";
        $page_link.="<a tabindex=\"0\" href=\"$var_file_url?p=".($cur_rre_nt_page-1)."$str_url\" class=\"first paginate_button\" id=\"DataTables_Table_0_previous\">Previous</a>";
        $page_link.=$total_pages>$page_limit?'...':'';

        for($i=$total_pages-$page_limit+1;$i<=$total_pages;$i++)
        {
            if($i==$cur_rre_nt_page)
            {
                $page_link.="<span class=\"paginate_active\">$i</span>";
            }
            else
            {
                $page_link.="<a href=\"$var_file_url?p=$i$str_url\" class=\"paginate_button\" id=\"DataTables_Table_$i\">$i</a>";
            }


        }
        $page_link.=($cur_rre_nt_page<$total_pages)?"<a tabindex=\"0\" href=\"$var_file_url?p=".($cur_rre_nt_page+1)."$str_url\" class=\"first paginate_button\" id=\"DataTables_Table_0_nextt\">Next</a>":"";
        $page_link.="<a tabindex=\"0\" href=\"$var_file_url?p=$total_pages$str_url\" class=\"last paginate_button\" id=\"DataTables_Table_0_last\">Last</a>";
    }
}
?>