【发布时间】:2021-05-08 08:48:10
【问题描述】:
我正在尝试使用准备好的 PDO 语句从我的数据库中获取一些产品。如果我将变量包含在 SQL 中,该公式效果很好,但当然这是非常糟糕的做法。
工作公式:
protected function getSomeProducts($somequantity){
$sql = "SELECT * FROM products ORDER by ID DESC LIMIT $somequantity";
$stmt = $this->connect()->query($sql);
$result = $stmt->fetchAll();
return $result;
我对准备好的语句的处理方法:
protected function getSomeProducts($somequantity){
$sql = "SELECT * FROM products ORDER by ID DESC LIMIT ?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$somequantity]);
$result = $stmt->fetchAll();
return $result;
}
这是我收到的错误消息:
致命错误 :未捕获的 PDOException:SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行的“6”附近使用的正确语法。
知道我做错了什么吗?
【问题讨论】:
-
我认为这可能是因为您将参数绑定到限制子句。看看这个问题。 stackoverflow.com/questions/2269840/…
标签: php mysql pdo prepared-statement