单个帖子MsSQL&的分页和查询字符串; PHP

时间:2016-03-03 17:26:55

标签: php sql-server pdo query-string

我编写了一个分页脚本来分页我博客中的所有帖子。现在我想创建和终结点,以便我可以转到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() ) ); 
}
?>

1 个答案:

答案 0 :(得分:1)

是一个帖子吗? 您可以按任意列对行进行排序,然后限制结果数量并根据请求的页面设置偏移量。 这是关于mysql的端点:MySQL Data - Best way to implement paging?

例如,如果请求页面如下:index.php?pageNum = 15并且您每页显示5个帖子, 使用$page = $_GET['pageNum']获取该值,并为结果编号和偏移量(LIMIT)设置PDO预处理语句。

声明$resultsPerPage = 5

SELECT * 
FROM Posts
LIMIT :offset, :maxResults 

推进那些准备好的陈述:

  • 偏移 - &gt; ($page - 1) * $resultsPerPage
  • maxResults - &gt; $resultsPerPage