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

标签 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>";

我不确定错误是什么,如何让这段代码工作? 我希望该方法是正确的,因为我无法对其进行测试。

最佳答案

你应该只使用LIMIT:

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

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

For compatibility with PostgreSQL, MySQL also supports the LIMIT row_count OFFSET offset syntax.

LIMIT 的有效示例如下:

LIMIT offset, row_count
LIMIT row_count
LIMIT row_count OFFSET offset

关于php - LIMIT 和 OFFSET 过滤数据库结果的问题(语法错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774976/

相关文章:

PHP strtotime : Get previous month

PHP 在没有数据库查询的情况下执行 SQL LIKE 匹配的方法?

php - 是否有适用于手动测试的代码覆盖工具?

MySQL 过程创建表语句语法错误

PHP 驱动的详尽统计数据 - 服务器端文本文件或 MySQL 表?

mysql - 如何从堆栈中的2个表中提取数据

php - PDO INSERT ON DUPLICATE KEY UPDATE 仅插入和更新 6 行

php - TinyMVC PDO 层在数据库查询时引发错误

php - PDO 和 PHP。未定义索引,但已定义

php - PDO (mysql) 参数号无效 : parameter was not defined