PDO PHP 以数字 ("2abcd") 开头的字符串输入在 $stmt->bindParam(':id', $id) 中被修剪为只有数字 ("2");

PDO PHP string input starting with number ("2abcd") gets trimmed to only number ("2") in $stmt->bindParam(':id', $id);

我在 PHP 中使用 PDO。每当我传递 $id = "2abcd"(带字符串后缀的数字)时,查询 returns 成功。 (数据为 $id=2)

在数据库中:id INT(11),img VARCHAR(100),uname VARCHAR(100)

 public static function getImagePath($id) {
    $sql_fetch_opp = "select img from my_user where id=:id";
        $db = DAO::connect();
    try {
        $stmt = $db->prepare($sql_fetch_opp);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $imgPath = $stmt->fetch(PDO::FETCH_COLUMN);
        return $imgPath;
    } catch (PDOException $e) {
        Err::log($e);
        throw new MyException(Err::PDO_EXCPTION);
    }
}

您只需要检查提供的值是否与您将其转换为整数后的值相同。如果不是,则抛出异常。

public static function getImagePath($id) {
    $sql_fetch_opp = "select img from my_user where id=:id";
        $db = DAO::connect();
    try {
        if((string)$id !== (string)(int)$id)
        {
            throw new PDOException("Invalid id provided");
        }
        $stmt = $db->prepare($sql_fetch_opp);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        $imgPath = $stmt->fetch(PDO::FETCH_COLUMN);
        return $imgPath;
    } catch (PDOException $e) {
        Err::log($e);
        throw new MyException(Err::PDO_EXCPTION);
    }
}

[jeroen]:(https://whosebug.com/users/42139/jeroen) 给出了正确的解决方案, 我需要检查

 if(!is_numeric($id))
      throw new MyException(Err::INVALID_ID);

这有效

$stmt->bindParam(':id', $id, PDO::PARAM_INT);