Search code examples
phpmysqlpdolimitoffset

Problems with LIMIT and OFFSET to filter database results (error in syntax)


I am trying to create a page where a user can search for a book, they type in the title and author - this is optional and also enter where the list returned should start from and the length of the list. Then a list of books shoud be returned with it's details.

When I try to run the code with print_r($stmt->errorInfo());, i get the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' authors = '' LIMIT '2' OFFSET '0'' at line 1 )

Here is the main code:

$title = $_GET["title"];
$authors = $_GET["authors"];
$start = (int)$_GET["start"];
$length = (int)$_GET["length"];

$sql = "SELECT title, authors, description, price
FROM book2
WHERE title LIKE '$title%' 
AND author LIKE '%$authors%'
OFFSET 0,$start
LIMIT 0,$length";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':authors', $authors);
$stmt->bindParam(':length', $_GET['length'], PDO::PARAM_INT);
$stmt->bindParam(':start', $_GET['start'], PDO::PARAM_INT);

     $stmt->execute(array(

    ':title' => $title,
    ':authors' => $authors,
    ':start' => $start,
     ':length' => $length   
      ));

print_r($stmt->errorInfo());

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

I'm not sure what the error is how to I get this code to work? I hope the method is correct to do so, as I can't test it.


Solution

  • You should use LIMIT only:

    $sql = "SELECT title, authors, description, price
    FROM book2
    WHERE title LIKE '$title%' 
    AND author LIKE '%$authors%'
    LIMIT $start,$length";
    

    The syntax with OFFSET is only for compatibility reason:

    For compatibility with PostgreSQL, MySQL also supports the LIMIT row_count OFFSET offset syntax.

    Valid examples of LIMIT are following:

    LIMIT offset, row_count
    LIMIT row_count
    LIMIT row_count OFFSET offset