如何在 SQL 查询中使用 PHP 变量

How can I use PHP variable in a SQL query

我正在使用 MySQL 和 PDO。如何在此查询中使用 PHP 变量?

像这样:

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

当我使用普通整数时,它可以正常工作并获取数据。

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

我试过这些,但没有用

$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);

先绑定再执行

$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);