带有for循环的安全PDO mySQL SELECT语句

时间:2014-10-04 01:15:13

标签: php mysql security for-loop pdo

我被告知使用PDO安全地从数据库中检索数据。现在,我想知道这是否安全或根本不起作用:

$dbtype     = "sqlite";
$dbhost     = "localhost";
$dbname     = "test";
$dbuser     = "root";
$dbpass     = "admin";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$firstName = htmlspecialchars($_POST["firstName"]);
foreach($conn->query('SELECT * FROM employeeTable WHERE firstName = ' . $firstName) as $row) {
    echo $row['lastName'].' '.$row['email'];
}

因为对我来说,看起来仍然可以注射"进入查询的东西。

所以我的问题是:这是否真的安全,如果不是,我将如何确保安全?

2 个答案:

答案 0 :(得分:3)

我认为您最好使用以下方法进行准备,准备过程是使注射无效

$sql = 'SELECT * FROM employeeTable WHERE firstName = :firstName';
$sth = $conn->prepare($sql); 
$sth -> bindParam(':firstName', $firstName);
$sth -> execute();
$result = $sth->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $key => $value) {
    echo $value->lastName, $value->email;
}

答案 1 :(得分:2)

请记住,不要将post变量直接连接到查询,只需使用预准备语句即可。在执行预准备语句之后,您需要获取结果:

$select = $conn->prepare('SELECT * FROM employeeTable WHERE firstName = :firstName');
$select->execute(array(':firstName' => $_POST["firstName"));

while($row = $select->fetch(PDO::FETCH_ASSOC))
    echo $row['lastName'].' '.$row['email'];
}

这是一个很好的阅读:

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers