我的 PDO 准备好的语句不适用于 fetchALL 和 Limit

问题描述

我正在尝试使用准备好的 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”附近使用的正确语法。

知道我做错了什么吗?

解决方法

替换下面一行

$stmt->execute([$somequantity]);

$stmt->bindParam(1,$somequantity,PDO::PARAM_INT);
$stmt->execute();