分页和错误

时间:2015-06-28 20:15:42

标签: php mysql

我正在尝试编写一个小的分页系统,但就事情而言,我收到了一个错误。这是我的代码:

<!-- 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篇文章等等。到目前为止,我所得到的只是这个错误:

  

致命错误:带有消息'SQLSTATE [42000]的未捕获异常'PDOException':语法错误或访问冲突:1064 SQL语法中有错误;检查与MySQL服务器版本相对应的手册,以便在/Applications/MAMP/htdocs/index.php:24的第1行''''附近使用正确的语法。堆栈跟踪:#0 / Applications / MAMP / htdocs /index.php(24):第24行/Applications/MAMP/htdocs/index.php中抛出的PDOStatement-&gt; execute()#1 {main}

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

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

2 个答案:

答案 0 :(得分:1)

您收到此错误,因为生成的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();

答案 1 :(得分:0)

也许这个?

$offset = $_GET['pg'] * 5;
$query = $db->prepare("SELECT * FROM posts ORDER BY id DESC LIMIT 5 OFFSET ':n'");
$query->execute(array(':n' => $offset);

编辑:

好的,这段代码应该有效。

$sql = "SELECT `password` FROM `users` WHERE `username` = :username";
$stmt = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$query = $stmt->execute(array(':username' => $username));
$rows = $query->fetchAll();
if (empty($rows)) {

}

只需根据您的需要进行修改。