How can I use PHP variable in a SQL query

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);
No answers yet

Question Overview

1 Followers
990 Views
Last Asked 3 years ago