预计的PDO声明:这是对的吗?

时间:2013-09-10 21:09:21

标签: php sql pdo sql-injection

我真的只是想检查这个语句的语法,并确保它是一个从sql注入安全的语句。有人可以帮我查一下,让我知道吗?

$lookupusername= $conn->prepare('SELECT * FROM users WHERE ID =":userId"');
$lookupusername->bindParam(':userId', $userid, PDO::PARAM_STR, 12);
$row = $lookupusername->fetch();
$username = $row['username'];
$usercountry = $row['country'];
if ($username == ""){
header('Location: index.php');
}

还有这句话:

$sql = $conn->query('SELECT description, city, status, state, country, needsusername, howmanypeopleneeded, howmanypeoplesignedup, needs.orgname, needs.ID, titleofneed, expiredate, datesubmitted, datetime FROM needs INNER JOIN follow ON follow.followname = needs.needsusername WHERE follow.username=' . $conn->quote($username) . ' AND needs.christmas="0" AND needs.status="posted" ORDER BY datesubmitted DESC');
while ($frows = $sql->fetch()) {

最终代码:

$lookupusername= $conn->prepare('SELECT * FROM users WHERE ID=:userid');
$lookupusername->bindParam(':userid', $userid);
$lookupusername->execute();
$row = $lookupusername->fetch();
$username = $row['username'];
$usercountry = $row['country'];

我没有执行准备好的声明。

1 个答案:

答案 0 :(得分:3)

我建议使用conn->[execute][1]代替[query][2]。因为那将是一个真正准备好的陈述,而不是你需要逃避的陈述。

SELECT * FROM users WHERE ID =:userID

然后做:

bindParam(':userId', $userId, PDO::PARAM_STR, 12);

就恶意内容而言,我假设有一秒钟我传给你userId,如下所示:

<script>alert('Hi')</script>  

现在我们还假设您将userId显示给管理员或其他用户。我可能会注入将在以后执行的恶意代码。因此,您仍必须注意确保正确转义返回给用户的数据。但是在大多数情况下,绑定参数将阻止任意SQL执行。

功能代码:

$sql= $conn->prepare('SELECT * FROM users WHERE ID =:userID');
$sql->bindParam(':userId', $userId, PDO::PARAM_STR, 12);