php - 使用 $_GET [""增加 PHP 和 SQL 的页面]

标签 php mysql database pdo blogs

最近忙于写博客,却卡在了增加页数、偏移量和限制。它应该对页面进行计数,并在单击按钮时每页显示 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

我希望有人能帮助我。

最佳答案

当您对 SQL 注入(inject)持开放态度时,可以使用以下方法解决逻辑问题:

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

关于php - 使用 $_GET [""增加 PHP 和 SQL 的页面],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37491477/

相关文章:

python - python中使用mysql报错1064

php - MYSQL PDO 从 fetchAll 中获取多行不工作

PHP 将 utf8 Æ (195 134) 转换为 198

php - 从 MySQL 数据库中获取特定值

mysql - mysql中如何根据组添加自增id

mysql - 在SQL中,两个表可以互相引用吗?

java - 我的更改密码界面在 java eclipse web 应用程序上不起作用

Java-连接池中的数据库连接管理

php - 第 3 行 MYSQL 语法错误

php - 如何选择某些元键的所有元值?