What are the best practices for handling form submissions and database interactions in PHP?

When handling form submissions in PHP, it is important to sanitize and validate user input to prevent SQL injection and other security vulnerabilities. It is also best practice to use prepared statements when interacting with a database to prevent SQL injection attacks. Additionally, error handling should be implemented to provide informative messages to the user in case of any issues.

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate user input
    $username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
    $password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);

    // Connect to the database
    $conn = new mysqli("localhost", "username", "password", "database");

    // Check for database connection errors
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Prepare and execute a SQL query using prepared statements
    $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();

    // Close the database connection
    $stmt->close();
    $conn->close();

    echo "Form submitted successfully!";
}