同时使用 PDO 准备好的语句和 filter_var?
嘿伙计们,我正在学习 OO PHP,并且一直在研究 PDO——但我不清楚的一件事是我是否应该将 PDO 准备好的语句与 filter_var() 函数或单独使用。例如,我应该做什么
$query = $database->connection->prepare("SELECT name FROM acounts WHERE id = :id LIMIT 1");
$query->bindParam(":id", $this->id, PDO::PARAM_INT);
或类似的事情?
$id = filter_var($this->id, FILTER_VALIDATE_INT);
$query = $database->connection->prepare("SELECT name FROM acounts WHERE id = :id LIMIT 1");
$query->bindParam(":id", $id, PDO::PARAM_INT);
Hey guys, I'm learning OO PHP, and have been looking into PDO -- One thing I'm not clear on though is whether I should be using PDO prepared statements in conjunction with the filter_var() function or just by themselves. For instance, should I be doing
$query = $database->connection->prepare("SELECT name FROM acounts WHERE id = :id LIMIT 1");
$query->bindParam(":id", $this->id, PDO::PARAM_INT);
or something like this?
$id = filter_var($this->id, FILTER_VALIDATE_INT);
$query = $database->connection->prepare("SELECT name FROM acounts WHERE id = :id LIMIT 1");
$query->bindParam(":id", $id, PDO::PARAM_INT);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,这是不同的任务。
您可以根据需要验证您的数据。
但 PDO 本身不需要任何验证。
对于您提供的代码,不需要使用 filter_var() ,因为带有 PDO::PARAM_INT 标志的 bindParam 将执行相同的工作
Generally speaking it's different tasks.
You can validate your data as you wish.
But PDO itself do not need any validations.
For the code you provided, using filter_var() is unnecessary, as bindParam with PDO::PARAM_INT flag will do the same job
参数化查询在这里就足够了。您已经从局部变量中获得了 ->$id 。 PDO 方法非常适合防范数据库攻击。
您首先必须区分 $id 是从哪里获得的。无论您在何处导入 user/http 输入,都请使用 filter_var 。不要仅将其用于安全目的,而是为了以正确的格式检索用户数据。
The parameterized query is sufficient here. You already got your ->$id from a local variable. And the PDO method is perfectly fine for securing against database exploits.
You have to differentiate on where you got the $id from in the first place. Use filter_var wherever you import user/http input. Don't use it for security purposes only, but with the goal to retrieve user data in the right format.