問(wèn)題描述
我有點(diǎn)困惑,為什么我們需要指定我們?cè)?Php 中的 PDO 中的 bindParam() 函數(shù)中傳遞的數(shù)據(jù)類型.例如這個(gè)查詢:
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();
如果我不指定第三個(gè)參數(shù),是否存在安全風(fēng)險(xiǎn).我的意思是如果我只是在 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);
推薦答案
對(duì)類型使用 bindParam()
可以被認(rèn)為更安全,因?yàn)樗试S更嚴(yán)格的驗(yàn)證,進(jìn)一步防止 SQL 注入.但是,如果您不這樣做,我不會(huì)說(shuō)會(huì)涉及真正 安全風(fēng)險(xiǎn),因?yàn)楦嗟氖悄鷪?zhí)行了prepared statement 比類型驗(yàn)證更能防止 SQL 注入.實(shí)現(xiàn)此目的的更簡(jiǎn)單方法是簡(jiǎn)單地將數(shù)組傳遞給 execute()
函數(shù),而不是使用 bindParam()
,如下所示:
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
));
您沒(méi)有義務(wù)使用字典,您也可以像使用問(wèn)號(hào)一樣使用字典,然后將其按相同的順序放入數(shù)組中.然而,即使這很完美,我還是建議養(yǎng)成使用第一個(gè)的習(xí)慣,因?yàn)橐坏┻_(dá)到一定數(shù)量的參數(shù),這種方法就會(huì)變得一團(tuán)糟.為了完整起見(jiàn),這里是它的樣子:
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));
這篇關(guān)于為什么需要在bindParam()中指定參數(shù)類型?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!