使用PDO从表中检索第n条记录时出错

时间:2017-01-24 09:54:35

标签: php mysql pdo

我正在使用以下脚本从表中检索第n条记录:

if($last_published_fb < $numposts){
    $last_published_fb--;
    // retrieve first post with id > last_published_fb
    $connect = dbconn(PROJHOST, POSTSDB, POSTSUSR, POSTSPWD);
    $sql = "SELECT * FROM tblposts ORDER BY id LIMIT :max,1";
    $query = $connect->prepare($sql);
    $query->bindParam(':max', $last_published_fb);
    if($query->execute()) {
        $rows = $query->fetchObject();
        $newid = ($rows ? $rows->id : null);
        echo 'to be published: ' . $newid;
    }
}

基本上,如果 $ last_published_fb 为0,我需要从表中检索第1行,如果是4,我需要第5行,依此类推。但是,上面的代码拒绝工作并在SQL语句中抛出语法错误。我错过了什么吗?这是错误消息:

PHP 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',1' at line 1' in /xxxx/xxx/xxx/posts.php:39

1 个答案:

答案 0 :(得分:0)

尝试将$ last_published_fb转换为整数

 $query->bindParam(':max', (int) $last_published_fb, PDO::PARAM_INT);