How can PHP code readability and maintainability be improved in the provided code snippet?
The provided code snippet lacks proper indentation and spacing, making it difficult to read and maintain. To improve readability and maintainability, we can add consistent indentation, spacing, and comments to clearly explain the purpose of each section of code.
<?php
// Retrieve user input from form
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// Validate user input
if (empty($username) || empty($email) || empty($password)) {
die("Please fill out all fields.");
}
// Sanitize user input
$username = filter_var($username, FILTER_SANITIZE_STRING);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$password = password_hash($password, PASSWORD_DEFAULT);
// Store user data in database
$query = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $query);
if ($result) {
echo "User registered successfully.";
} else {
echo "Error registering user.";
}
?>
Related Questions
- How can the input handling process be optimized using PHP arrays or loops in this scenario?
- What considerations should be made when deciding between using sessions or URL parameters for language management in a PHP application?
- What is the common error message "Forbidden: You don't have permission to access" related to PHP form submission?