微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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('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();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐