LIMIT和OFFSET过滤数据库结果的问题(语法错误)

时间:2015-04-21 14:21:58

标签: php mysql pdo limit offset

我正在尝试创建一个用户可以搜索图书的页面,他们输入标题和作者 - 这是可选的,也可以输入列表返回的位置和列表的长度。然后,将返回一份书籍清单及其详细信息。

当我尝试使用print_r($ stmt-> errorInfo());运行代码时,我收到错误:

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 ' authors = '' LIMIT '2' OFFSET '0'' at line 1 )

这是主要代码:

$title = $_GET["title"];
$authors = $_GET["authors"];
$start = (int)$_GET["start"];
$length = (int)$_GET["length"];

$sql = "SELECT title, authors, description, price
FROM book2
WHERE title LIKE '$title%' 
AND author LIKE '%$authors%'
OFFSET 0,$start
LIMIT 0,$length";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':authors', $authors);
$stmt->bindParam(':length', $_GET['length'], PDO::PARAM_INT);
$stmt->bindParam(':start', $_GET['start'], PDO::PARAM_INT);

     $stmt->execute(array(

    ':title' => $title,
    ':authors' => $authors,
    ':start' => $start,
     ':length' => $length   
      ));

print_r($stmt->errorInfo());

echo "<table>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$authors = $row['authors'];
$description = $row['description'];
$price = $row['price'];

echo "<tr>";
        echo "<td>Title</td>";
        echo "<td>$title</td>";
echo "</tr>";
echo "<tr>";
        echo "<td>Authors</td>";
        echo "<td>$authors</td>";
echo "</tr>";
echo "<tr>";
        echo "<td>Description</td>";
        echo "<td>$description</td>";
echo "</tr>";
echo "<tr>";
        echo "<td>Price</td>";
        echo "<td>$price</td>";
echo "</tr>";
}
echo "</table>";

我不确定错误是什么让我的代码工作? 我希望这种方法是正确的,因为我无法测试它。

2 个答案:

答案 0 :(得分:3)

您应该只使用LIMIT

$sql = "SELECT title, authors, description, price
FROM book2
WHERE title LIKE '$title%' 
AND author LIKE '%$authors%'
LIMIT $start,$length";

OFFSET的语法仅出于兼容性原因:

  

为了与PostgreSQL兼容,MySQL还支持LIMIT row_count OFFSET偏移语法。

LIMIT的有效示例如下:

LIMIT offset, row_count
LIMIT row_count
LIMIT row_count OFFSET offset

答案 1 :(得分:2)

$sql = "SELECT title, authors, description, price
FROM book2
WHERE title LIKE '$title%' 
AND author LIKE '%$authors%'

在顶行显示authors在底部author。由于提供的错误,我会说author是正确的,你应该删除authors中的s

althogh检查cascaval关于限制的答案。修复author后,您可能会在代码中遇到第二个错误,并且cascavals答案可以帮助您解决问题。