What are some best practices for securely handling user registration and database management in PHP to prevent security vulnerabilities?

Issue: To prevent security vulnerabilities in user registration and database management in PHP, it is important to properly sanitize user input, use prepared statements to prevent SQL injection attacks, hash passwords before storing them in the database, and implement proper error handling to avoid leaking sensitive information.

// Sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

// Hash password before storing in the database
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->execute();

// Implement proper error handling
if($stmt->rowCount() > 0) {
    echo "User registered successfully";
} else {
    echo "Error registering user";
}