-3

I am using MySQL and PDO. How can I use PHP variable in this query?

Like this:

$startFrom = 0;
$perPage = 12;
$query = $db->prepare("SELECT * FROM products LIMIT $startFrom, $perPage");
$query->execute();
$products = $query->fetchAll();
var_dump($products);

It works and fetches data when I use normal integers.

$query = $db->prepare("SELECT * FROM products LIMIT 0, 10");
$query->execute();
$products = $query->fetchAll();
var_dump($products);

I tried these, but they didn't work

$startFrom = 0;
$perPage = 12;
$query = $db->prepare("SELECT * FROM products LIMIT ?,?");
$query->execute(array($startFrom, $perPage));
$products = $query->fetchAll();
var_dump($products);

$startFrom = 0;
$perPage = 12;
$query = $db->prepare("SELECT * FROM products LIMIT :startFrom, :perPage");
$query->execute(array("startFrom" => $startFrom, "perPage" => $perPage));
$products = $query->fetchAll();
var_dump($products);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
MrRE
  • 11
  • 5
  • 2
    Dit you search online? https://www.php.net/manual/en/pdostatement.bindparam.php . These are the basics for php pdo. Please show some effort and at least try to find the answer before asking it here – Gert B. Aug 27 '21 at 07:48
  • This might shed some light on it: https://stackoverflow.com/questions/18005593/parametrized-pdo-query-and-limit-clause-not-working – droopsnoot Aug 27 '21 at 07:51

1 Answers1

1

First bind then execute

$startFrom = 0;
$perPage = 12;
$query = $db->prepare("SELECT * FROM products LIMIT ?,?");
$query->bind_param('ii', $startFrom, $perPage);
$query->execute();
$products = $query->fetchAll();
var_dump($products);
S N Sharma
  • 1,436
  • 2
  • 7
  • 20