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

时间:2015-04-20 15:41:58

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

到目前为止,它确实只返回了我在输入中键入的内容 - 所以根本没有!有谁知道我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

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

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

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