加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 分页和错误

发布时间:2020-12-13 15:56:48 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试编写一个小的分页系统,但就事情而言,我收到了一个错误.这是我的代码: !-- something before that's working well -- else{ include('head.php'); if(empty($_GET['pg'])){ $_GET['pg'] = 0 ;} $offset = $_GET['pg'] * 5; $query = $db-prepare('
我正在尝试编写一个小的分页系统,但就事情而言,我收到了一个错误.这是我的代码:

<!-- something before that's working well -->    
else{
    include('head.php');
    if(empty($_GET['pg'])){ $_GET['pg'] = 0 ;}
    $offset = $_GET['pg'] * 5;
    $query = $db->prepare('SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET :n');
    $query->bindParam(':n',$offset);
    $query->execute();
?>
<body>
<?php 
    while ($data = $query->fetch()){
        echo '<article>'.$data['content'].'</article>';
       }}?>

   </body>

所以我只想逐页显示5篇文章.也就是说,我想要索引页面上的最后5篇文章(即第0页),然后是第1页上的接下来的5篇文章等等.到目前为止,我得到的只是这个错误:

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 MySQL server version for the right syntax to use near ”0” at line 1’ in /Applications/MAMP/htdocs/index.php:24 Stack trace: #0 /Applications/MAMP/htdocs/index.php(24): PDOStatement->execute() #1 {main} thrown in /Applications/MAMP/htdocs/index.php on line 24

第24行是$query-> execute();指令.

所以我想我的问题是:发生了什么事?我的传呼系统是否按照我想要的方式工作?

解决方法

您收到此错误是因为生成的sql在0周围有引号字符.

‘SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET:n’
正在变成

‘SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET“0”’
当你需要的SQL是

‘SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET 0’ – 0周围没有引号

试试这个

$offset =  (int) ($_GET['pg'] * 5 ); // cast to an int so that you know its not a non-int value,then you don't need the protection of bind

$sql = 'SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET ' . $offset;

$query = $db->prepare($sql);

$query->execute();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读