使用PHP更新MySQL数据库是否有好的做法?我应该使用这段代码:
function change_email($email, $email_new) {
$sql = "UPDATE users SET email = '$email_new' WHERE email = '$email' LIMIT 1";
$this->_db->query($sql);
}
或者有更好的解决方案吗?我听说过准备好的陈述,我想我最好在这里使用它们,因为$ email和$ email_new是用户输入。
非常感谢。
答案 0 :(得分:3)
因此,要正确更新mysql数据库,最好使用PDO API:
function change_email($pdo, $email,$email_new)
{
$sql = "UPDATE users SET email = ? WHERE email = ?";
$pdo->prepare($sql)->execute([$email,$email_new]);
}
答案 1 :(得分:0)
如果你想以非OOP方式去做。你可以通过以下方式完成。但一定要先逃避数据(如果是用户输入),否则你很容易受到SQL注入攻击。
$email_new = mysqli_real_escape_string($db, $email_new); //If you didn't did this already
$email = mysqli_real_escape_string($db, $email);
//You could also use htmlentities to secure against cross-site scripting
$email_new = htmlentities($email_new); //You can use htmlspecialchars() if you only want to do minimum conversion.
//This is not needed for email cause you are not inserting it into the database.
$query = "UPDATE users SET email = '$email_new' WHERE email = '$email'";
mysqli_query($db, $query);
答案 2 :(得分:-1)
试试这个
$query = "UPDATE users SET email ='".$email_new."' WHERE email = '".$email."'";