【问题标题】:Increase pages with PHP and SQL with $_GET[""]使用 $_GET[""] 增加 PHP 和 SQL 页面
【发布时间】:2016-05-27 20:05:57
【问题描述】:

目前我正忙于写博客,但我被困在增加页面、偏移量和限制。它应该计算页面并在按钮单击时在每页显示 10 行。我有这个:

    <?php

$rowsPerPage = 10; //number of results you want to display 
$num = $_GET["page"]; //set the offset to start w/the num. of results (good for paging)
$offset = ($num - 1) * $rowsPerPage; // to offset the limit count 
$sql = "SELECT * FROM `posts` ORDER BY `id` DESC LIMIT ".$rowsPerPage." OFFSET ".$offset."";
$result = $conn->query($sql);
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
    echo '<div class="post-preview">
            <a href="posts.php?id='.$row["id"].'">
                <h2 class="post-title">
                    '.$row["title"].'
                </h2>
                <h3 class="post-subtitle">
                    '.$row["content"].'
                </h3>
            </a>
            <p class="post-meta"><a href="#">'.$row["creator"].'</a> | '.$row["date"].'</p>
        </div>
        <hr>';
    }       
    ?>

但它似乎只适用于 domain.com/index.php?page=1,它加载正常等。当我删除 '/index.php?page=1' 并转到没有设置 $_GET 的索引时我收到以下错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-10' at line 1' in /home/u9778802/public_html/blog/index.php:49 Stack trace: #0 /home/u9778802/public_html/blog/index.php(49): PDO->query('SELECT * FROM `...') #1 {main} thrown in /home/u9778802/public_html/blog/index.php on line 49

我希望有人可以帮助我。

【问题讨论】:

  • echo $sql 也是如此,看看您构建的查询是什么样的。并注意$_GET['page'] ISN'T 已定义,然后$offset 将变为-10,并且您不能有负偏移量。这也意味着您正在生成 undefined index 警告,该警告可能已被抑制/隐藏。

标签: php mysql database pdo blogs


【解决方案1】:

虽然您对 SQL 注入持开放态度,但可以使用以下方法解决逻辑问题:

$num = (isset($_GET["page"]) and is_int($_GET["page"])) ? $_GET["page"] : 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2014-10-15
    • 2012-01-08
    相关资源
    最近更新 更多