php - 根据用户搜索输入查找库详细信息 - 使用 LIMIT 和 OFFSET

标签 php mysql limit offset

基本上我在一个表单中有 4 个字段。我想让用户按书名或作者或两者在图书馆中搜索书籍。我还希望用户设置项目列表的长度和从起点开始,这些不是限制,但用户不必指定。

代码如下:

require_once __DIR__.'/config.php';
session_start();
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);

$title = $_GET["title"];
$authors = $_GET["authors"];
$st = $_GET["start"];
$ln = $_GET["length"];



$stmt = $dbh->prepare("SELECT title, authors, description, price FROM books  WHERE title = :title LIMIT :length OFFSET :start");
$stmt->execute(array(':title' => $title,':start' => $st,':length' => $ln));


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


echo "<table>";
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>";

到目前为止,它实际上只是返回我在输入中键入的内容 - 所以什么都没有!有谁知道我该怎么做?

最佳答案

以这种方式调整您的代码:

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

打印查询返回的所有行。您的代码只打印最后一行。

关于php - 根据用户搜索输入查找库详细信息 - 使用 LIMIT 和 OFFSET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29752350/

相关文章:

mysql - 从 MySQL 到 CSV 文件的列名

php - POST 方法和 GET 方法 - 单选按钮现在不起作用

php - 在 Laravel 中为 mysql 数据库制作模型和 Controller ?

php - 为什么这个 Mysql 查询不起作用

mysql查找丢失的项目

php - MySQL 使用 LIKE 或 REGEX 匹配数字列表

php - 当我检查一行时,为什么 MySQL 没有在 LIMIT 1 处停止?

gwt - GWT CellTables 有 15 行的限制吗?

sql - SQLServer 2000中的有效分页(限制)查询?

php - 为什么在 dockerfile 中运行的 composer install 命令中看不到卷目录中的 composer.json 文件?