問題描述
我有點困惑,為什么我們需要指定我們在 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();
如果我不指定第三個參數,是否存在安全風險.我的意思是如果我只是在 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 注入.但是,如果您不這樣做,我不會說會涉及真正 安全風險,因為更多的是您執行了prepared statement 比類型驗證更能防止 SQL 注入.實現此目的的更簡單方法是簡單地將數組傳遞給 execute()
函數,而不是使用 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
));
您沒有義務使用字典,您也可以像使用問號一樣使用字典,然后將其按相同的順序放入數組中.然而,即使這很完美,我還是建議養成使用第一個的習慣,因為一旦達到一定數量的參數,這種方法就會變得一團糟.為了完整起見,這里是它的樣子:
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()中指定參數類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!