【问题标题】:PDO bindParam return same result with wrong parameterPDO bindParam 返回相同的结果但参数错误
【发布时间】:2018-11-12 15:02:01
【问题描述】:
public function getStudent($id){
    $sth = $this->con->prepare("SELECT * FROM students WHERE id=:id");
    $sth->bindParam("id", $id, PDO::PARAM_INT);
    $sth->execute();
    $student = $sth->fetchObject();
    return $student;
}

(1)http://localhost/slim-framework/public/api/v1/student/1

(2)http://localhost/slim-framework/public/api/v1/student/1fgff

通过使用上面代码的“GET”请求,上面的 URL 1 和 2 给了我相同的结果,但假设不是。

请帮助我如何使 URL 2 标记错误,因为它不是整数?

【问题讨论】:

  • 这显然与 PDO 无关,而是验证输入数据。
  • 因为(int) '1' === 1(int) '1fgff' === 1。处理这个问题的最佳方法是检查 $id 是否为数字,在这种情况下引发错误。
  • 当您执行PDO::PARAM_INT 时,这会将变量转换为整数。删除它,您的代码应该会按预期失败。
  • 实际上,我开始做一些研究,结果证明我错了。 PDO::PARAM_INT 会将其转换为浮点数,而不是整数。看我的回答here

标签: php pdo slim


【解决方案1】:
public function getStudent($id){
    if(is_numeric($id)) {
        $sth = $this->con->prepare("SELECT * FROM students WHERE id=:id");
        $sth->bindParam("id", $id);
        $sth->execute();
        $sth->fetchObject();
        return true;
    }else {
        return false;
    }
}

我现在遵循@u_mulder 和@Federkun 的建议,使用 is_numeric() 方法检查 id 是否为整数。

感谢大家的努力。

【讨论】:

    【解决方案2】:

    你好,希望对你有帮助

    你的情况是

    public function getStudent(int $id){
     .......
    }
    

    如果 id 来自其他东西而不是 int 你会得到 php 错误

    http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

    【讨论】:

    • 声明 strict types 时会发生错误,否则 - 不会。
    • 可能还有另一个错误。使用$sth->bindParam(":id", $id, PDO::PARAM_INT); 而不是$sth->bindParam("id", $id, PDO::PARAM_INT);
    • @AramGrig 这没什么区别。冒号是可选的。
    • 好的,很抱歉没有帮到你
    猜你喜欢
    • 2013-03-29
    • 2015-12-27
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多