Search code examples
phpmysqlsqlpdosql-limit

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.

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

+----+---------------------+
| id | bookname            |
+----+---------------------+
| 12 | book.pdf            |
|  1 | book2.pdf           |
| 13 | book3.pdf           |
+----+---------------------+

But on the webpage I only get printed

book2
book3

P.S. : 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 ==:

while($row = $stmt->fetch(PDO::FETCH_ASSOC))

Solution

  • 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)) {
        ...
    }