I'm building a CRUD with pure PHP+PDO Mysql driver.
I've got a page that lists the data contained in a DB table and I want to implements some filters, but I'm stuck on binding paramenters to PDO with a dynamic query.
For example this code works well with and without the $_GET["op"]
.
$params = [];
$pag_query = "SELECT COUNT(*) FROM cells WHERE 1 ";
if(!empty($_GET["op"])){
$pag_query .= "AND op=:op ";
$params["op"] = $_GET["op"];
}
$stmt = db()->prepare($pag_query);
$stmt->execute($params);
$n_rows = $stmt->fetchColumn();
But I cannot make this query work.
<?php
//some logic here to get $limit and $offset
$params["limit"] = $limit;
$params["offset"] = $offset;
$tbl_query = "SELECT * FROM cells WHERE 1 ";
if(!empty($_GET["op"])){
$tbl_query .= "AND op=:op ";
$params["op"] = $_GET["op"];
}
$tbl_query .= "ORDER BY cid LIMIT :limit OFFSET :offset";
//Prepare the query
$stmt = db()->prepare($tbl_query);
$stmt->execute($params);
$table = $stmt->fetchAll();
It gives me this error message.
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''20' OFFSET '0'' at line 1 in C:\xampp\htdocs\celldb\manage.php on line 64
If I simulate the query on PhpMyadmin it works well and it works also if I remove if(!empty($_GET["op"])
case and pass $limit
and $offset
using $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);