可以在准备SQL之前绑定参数吗? PHP PDO

Can you bind parameters before preparing the SQL? PHP PDO

我与数据库交互的正常顺序是这样的:

$sql = "select count(*) from users where username = :newusername";
$statement = $databaseConnection->prepare($sql);
$statement->bindParam(":newusername", $newUsername, PDO::PARAM_STR);
$statement->execute();

...prepare 在 bindParam 之前调用。我可以在我的 bindParams 之后准备 SQL 还是行不通?这对于这个逻辑很方便:

$sql = "update users set suspended = :newsuspensionsetting";
$statement->bindParam(":newsuspensionsetting", $newSuspensionSetting, PDO::PARAM_INT);

if ($newUsernameHasBeenSet) {
    $sql .= ", username = :newusername";
    $statement->bindParam(":newusername", $newUsername, PDO::PARAM_STR);
}

if ($newPasswordHasBeenSet) {
    $newPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    $sql .= ", password = :newpassword";
    $statement->bindParam(":newpassword", $newPassword, PDO::PARAM_STR);
}

$sql .= "where permanent_id = :permanentidofusertochange";
$statement->bindParam(":permanentidofusertochange", $permanentIDOfUserToChange, PDO::PARAM_STR);

$statement = $databaseConnection->prepare($sql);
$statement->execute();

谢谢

如果满足条件,您应该创建一个关联数组并在其中添加值: 你的 if:

里面应该有这样的东西

$arr += ["keytobind"=>"value"]

当你的所有“ifs”都通过后,你就可以使用 prepare 语句和你的 prepare 方法。

最后,使用: foreach($arr as $key=>$value){$statement->bindParam(":".$key,$value); }