我想对准备好的语句以及它们以其他方式组装时的行为进行一些澄清。
下面的示例代码来自Straight out this W3 entry 。我的问题是,由于值比本示例中提供的四个值多得多,我希望将它们存储在数组中,然后运行 foreach 来准备每个字符串。
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
etc
下面的编辑对应用程序来说是否安全,或者它是否破解了准备好的语句的全部要点?
$stuff = array("firstname", "lastname", "email");
foreach ($stuff as $singlestuff) {
$singlestuff1 = ':'.$singlestuff;
$singlestuff2 = '$'.$singlestuff;
$stmt = $conn->prepare("INSERT INTO MyGuests ($singlestuff1) ) VALUES ($singlestuff2)");
$stmt->bindParam($singlestuff1, $singlestuff2);
}
对于任何宏观错误,我们深表歉意,代码只是概念的说明。
提前致谢!
最佳答案
在 foreach 循环内绑定(bind),假设变量存在:
foreach ($stuff as $singlestuff) {
$stmt->bindParam(':' . $singlestuff, $$singlestuff);
}
关于php - PDO 准备好的语句中的 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33637729/