为什么我们需要在bindParam()中指定参数类型? [英] Why do we need to specify the parameter type in bindParam()?

查看:122
本文介绍了为什么我们需要在bindParam()中指定参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于为什么我们需要指定在Php的PDO中的bindParam()函数中传递的数据类型,我有些困惑.例如,以下查询:

I am a bit confuse as to why we need to specify the type of data that we pass in the bindParam() function in PDO in Php. For example this query:

$calories = 150; 
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT); 
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();

如果未指定第3个参数,是否存在安全风险.我的意思是,如果我只是在bindParam()中这样做:

Is there a security risk if I do not specify the 3rd parameter. I mean if I just do in the bindParam():

$sth->bindParam(1, $calories); 
$sth->bindParam(2, $colour);

推荐答案

bindParam()与类型一起使用可能被认为更安全,因为它允许更严格的验证,从而进一步防止了SQL注入.但是,如果您不这样做,我不会说这会涉及真正的 安全风险,因为更重要的是,您进行

Using bindParam() with types could be considered safer, because it allows for stricter verification, further preventing SQL injections. However, I wouldn't say there is a real security risk involved if you don't do it like that, as it is more the fact that you do a prepared statement that protects from SQL injections than type verification. A simpler way to achieve this is by simply passing an array to the execute() function instead of using bindParam(), like this:

$calories = 150; 
$colour = 'red';

$sth = $dbh->prepare('SELECT name, colour, calories
                      FROM fruit
                      WHERE calories < :calories AND colour = :colour');

$sth->execute(array(
    'calories' => $calories,
    'colour' => $colour
));

您没有义务使用字典,也可以像对问号那样使用字典,然后将其以相同的顺序放入数组中.但是,即使此方法工作完美,我还是建议养成使用第一个方法的习惯,因为一旦您达到一定数量的参数,此方法就变得一团糟.为了完整起见,它是这样的:

You're not obligated to use a dictionary, you can also do it just like you did with questionmarks and then put it in the same order in the array. However, even if this works perfectly, I'd recommend making a habit of using the first one, since this method is a mess once you reach a certain number of parameters. For the sake of being complete, here's what it looks like:

$calories = 150; 
$colour = 'red';

$sth = $dbh->prepare('SELECT name, colour, calories
                      FROM fruit
                      WHERE calories < ? AND colour = ?');

$sth->execute(array($calories, $colour));

这篇关于为什么我们需要在bindParam()中指定参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆