This question already has an answer here:
Below shows the php code that I am using to register users into the system. I want to make it secure using prepare statement. Please help me on how to put prepare method to make it secure.
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);
}
}
</div>
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);
}
}
This is using procedural style and the MySQLi extension. Do note that you are using MySQL which is deprecated so it is recommended to switch to MySQLi