分页和查询字符串为个别文章MSSQL&PHP

问题描述 投票:0回答:1

我在我的博客上写了一个分页脚本页面中的所有帖子。现在,我想创建和端点,这样我可以去mydomain/index.php?blogID1mydomain/index.php?blogID2mydomain/index.php?blogID3mydomain/index.php?blogID4等。

我在哪里可以读到这样做,以及如何实现它的最简单的方法可能,鉴于我目前的脚本:

<?php
        $rowsPerPage = 2;
        try
        {
            $conn = new PDO( "sqlsrv:server=localhost ; Database=blog", "******", "*******");
            $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        }
        catch(Exception $e)
        { 
            die( print_r( $e->getMessage() ) ); 
        }

        try
        {
            $tsql = "SELECT COUNT(blogID) FROM blog_posts";
            $stmt = $conn->query($tsql);
            $rowsReturned = $stmt->fetch(PDO::FETCH_NUM);
            if($rowsReturned[0] == 0)
            {
                echo "No rows returned.";
            }
            else
            {     
                $numOfPages = ceil($rowsReturned[0]/$rowsPerPage);  
                for($i = 1; $i<=$numOfPages; $i++)     
                {
                    $pageNum = "index.php?pageNum=$i";
                    print("<a href='$pageNum' class='btn btn-primary active btn-sm'>$i</a>&nbsp;&nbsp;");
                }
            }
            $tsql = "SELECT * FROM 
            (SELECT ROW_NUMBER() OVER(ORDER BY blogID DESC) 
               AS RowNumber,
               blog_title,    
               blog_post,
               blog_author,
               blog_category,
               blog_date,
               blogID
               FROM blog_posts)
AS Temp
WHERE RowNumber BETWEEN ? AND ?";
$stmt2 = $conn->prepare($tsql);
if(isset($_GET['pageNum']))
{
$highRowNum = $_GET['pageNum'] * $rowsPerPage;
$lowRowNum = $highRowNum - $rowsPerPage + 1;
}
else
{
$lowRowNum = 1; 
$highRowNum = $rowsPerPage; 
}
$params = array(&$lowRowNum, &$highRowNum);
$stmt2->execute(array($lowRowNum, $highRowNum));
while($row = $stmt2->fetch(PDO::FETCH_NUM) )
{
echo   "$row[1]"; 
echo   "$row[2]";
echo   "$row[3]"; 
echo   date_format( new DateTime($row['5']), 'd M Y, H:i' ); 
echo  "$row[4]"; 
echo  "$row[6]";

}
}
catch(Exception $e)
{ 
die( print_r( $e->getMessage() ) ); 
}
?>
php sql-server pdo query-string
1个回答
1
投票

是排帖子?您可以通过任何一列命令你行,则限制结果的数量和偏移量取决于被请求的页面设置。下面是关于MySQL的端点:MySQL Data - Best way to implement paging?

例如,如果页面被请求是这样的:的index.php页次= 15,你是显示每页5个员额,抓住与$page = $_GET['pageNum']该值和设置您的PDO准备的结果数量和偏移量(LIMIT)语句。

声明$resultsPerPage = 5

SELECT * 
FROM Posts
LIMIT :offset, :maxResults 

并将其推入那些准备语句:

  • 偏移 - > ($page - 1) * $resultsPerPage
  • 的maxResults - > $resultsPerPage
© www.soinside.com 2019 - 2024. All rights reserved.