What are best practices for handling form submissions and database queries 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 querying a database to protect against SQL injection attacks. Additionally, error handling should be implemented to gracefully handle any issues that may arise during form submission or database queries.

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST["name"]);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    
    // Validate input
    if (empty($name) || empty($email)) {
        echo "Please fill out all fields";
    } else {
        // Connect to database
        $conn = new mysqli("localhost", "username", "password", "database");
        
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        
        // Prepare and execute SQL query
        $stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->bind_param("ss", $name, $email);
        
        if ($stmt->execute()) {
            echo "Record added successfully";
        } else {
            echo "Error: " . $stmt->error;
        }
        
        // Close connection
        $stmt->close();
        $conn->close();
    }
}