LIMIT使用偏移误差

时间:2016-03-04 10:49:54

标签: php mysql pdo

我使用Ajax加载项目,并使用偏移量

JS:

var offset = 0;

$(".load-more").click(function() {
    offset+=5;
    $(this).addClass("spin");
    $.ajax({
      url: '/api/fetchitems.php?offset='+offset+'&sort='+sort,
      success: function(data){
        $(".load-more").before(data);
      }
    });
});

PHP / SQL:

$offset = intval($_GET["offset"]);

$stmt = $db->prepare(
 "SELECT s.id,s.date,s.title,s.views,s.image,s.hidpi,s.width,s.description,u.display_name,u.avatar, s.hotness
  FROM showcase AS s
  INNER JOIN users AS u ON s.user_id = u.id
  UNION ALL
  SELECT q.id,q.date,q.title,q.views,0,0,0,q.text,u.display_name,u.avatar, q.hotness
  FROM questions AS q
  INNER JOIN users AS u ON q.user_id = u.id
  ORDER BY hotness DESC
  LIMIT :skip, 5
  ");
$stmt->bindParam(":skip",$offset);
$stmt->execute();
$items = $stmt->fetchAll();
$stmt = null;

我在执行时收到此错误:

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 ''5', 5' at line 9' in **** Stack trace: #0 **** PDOStatement->execute() #1 {main} thrown in

当我在phpMyAdmin中运行SQL时,它运行正常。

2 个答案:

答案 0 :(得分:4)

你的:skip被包裹在引号中,好像它是一个字符串(因为默认设置是PDO::PARAM_STR),这是错误的,你现在得到:

LIMIT '5',5;

根据documentation,您可以将类型更改为int:

$stmt->bindParam(":skip",$offset, PDO::PARAM_INT);

这在PhpMyAdmin中起作用的原因是因为您没有添加单引号。

答案 1 :(得分:0)

$stmt = $db->prepare(
 "SELECT s.id,s.date,s.title,s.views,s.image,s.hidpi,s.width,s.description,u.display_name,u.avatar, s.hotness
  FROM showcase AS s
  INNER JOIN users AS u ON s.user_id = u.id
  UNION ALL
  SELECT q.id,q.date,q.title,q.views,0,0,0,q.text,u.display_name,u.avatar, q.hotness
  FROM questions AS q
  INNER JOIN users AS u ON q.user_id = u.id
  ORDER BY hotness DESC
  LIMIT :skip, 5 
  ");

$stmt->bindParam(':skip', $offset, PDO::PARAM_INT);

你想这样做