如何在mysqli_query和mysql_query中设置prepare security语句?

时间:2014-04-10 21:05:31

标签: php html mysql validation set

下面显示了我用来将用户注册到系统中的php代码。我想使用prepare语句使其安全。请帮助我如何使用准备方法使其安全。

if (!isset($_POST['submit']))        {
     $user_name = $_POST['username']; 
      $user_password = crypt($_POST['password']); 
      $user_email = $_POST['email']; 

if($user_name && $user_password && $user_email)
    {
                // register user
        $query = mysql_query("INSERT INTO users (username, password, email, type) 
        VALUES ('$user_name', '$user_password', '$user_email', '0')");
        mysql_query($query); 

}
 }

1 个答案:

答案 0 :(得分:0)

if (isset($_POST['submit'])) { // Note: I removed the exclamation mark before isset because it made no sense
    $user_name = $_POST['username']; 
    $user_password = crypt($_POST['password']); 
    $user_email = $_POST['email']; 

    if($user_name && $user_password && $user_email) {
        $link = mysqli_connect('localhost', 'user', 'password', 'database');
        $stmt = mysqli_stmt_init($link);
        mysqli_stmt_prepare($stmt, "INSERT INTO `users` (`username`, `email`, `password`, `type`) VALUES (?,?,?)");
        mysqli_stmt_bind_param($stmt, 'sssi', $user_name, $user_password, $user_email, 0);
        mysqli_stmt_execute($stmt);
    }
}

这是使用过程样式和MySQLi扩展。请注意您使用的是不推荐使用的MySQL,因此建议切换到MySQLi