[英]PDO MySQL LIMIT query unexpected result
I'm trying to show a list of files and create a basic pagination system.我正在尝试显示文件列表并创建一个基本的分页系统。 I'm stuck on this one because the output of the MySQL query with PDO is different than within MySQL itself.
我被困在这个问题上,因为 MySQL 查询的 output 与 PDO 本身不同。
Here's the code part:这是代码部分:
$sql = "SELECT * FROM libri ORDER BY bookname;";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row > 0) {
// output data of each row
$countStart = ($page-1)*$page;
//Listing da database
$sql = "SELECT * FROM libri ORDER BY bookname LIMIT 0,3";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$book = $row["bookname"];
$path = $host."/libreria/lib-folder/".$row["bookname"];
$truepath = basename($path);
$coverName = $truepath."-cover.png";
$fileArr = explode('.', $book);
$fileExt = strtolower(end($fileArr));
echo "<a href='$truepath'>".$row["bookname"]."</a><br>";
What it's bugging me is that the query with LIMIT is behaving differently than what I see on mysql: on mysql CLI with the same query i get困扰我的是,带有 LIMIT 的查询的行为与我在 mysql 上看到的不同:在 mysql CLI 上,我得到的查询相同
+----+---------------------+
| id | bookname |
+----+---------------------+
| 12 | book.pdf |
| 1 | book2.pdf |
| 13 | book3.pdf |
+----+---------------------+
But on the webpage I only get printed但在网页上我只得到打印
book2
book3
PS : i'm still unsure also of the reason why the lines get printed only with this seemingly wrong while
statement, but not with the correct comparison ==
: PS:我仍然不确定为什么仅使用这个看似错误的
while
语句打印行的原因,而不是正确的比较==
:
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
You are fetching once before you enter the loop, resulting in the first row being basically bypassed before it gets a chance to be printed.您在进入循环之前获取一次,导致第一行在有机会被打印之前基本上被绕过。 Just remove this unwanted fetch and your code should behave as you expect it to.
只需删除这个不需要的提取,您的代码就会按照您的预期运行。
$sql = "SELECT * FROM libri ORDER BY bookname LIMIT 0,3";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC); # --> here
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.