【问题标题】:Finding library details based on user search input - using LIMIT and OFFSET根据用户搜索输入查找库详细信息 - 使用 LIMIT 和 OFFSET
【发布时间】:2015-04-20 15:41:57
【问题描述】:

基本上我在一个表单中有 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>";

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

【问题讨论】:

    标签: php mysql limit offset


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,它很有帮助,但现在它什么也没有返回。
    • 你得到了什么?什么样的错误?你有没有在mysql中尝试过你的查询,看看它是否返回任何结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2012-04-03
    • 2018-06-29
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多