How can PHP be used to validate form data against a MySQL database?

When validating form data against a MySQL database using PHP, you can first retrieve the form data submitted by the user and then query the database to check if the data matches any existing records. If a match is found, you can display an error message to the user indicating that the data is already in use.

<?php

// Assuming form data is submitted via POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    
    // Connect to MySQL database
    $conn = mysqli_connect("localhost", "username", "password", "database");
    
    // Check if username already exists in the database
    $query = "SELECT * FROM users WHERE username = '$username'";
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) > 0) {
        echo "Username already exists. Please choose a different one.";
    } else {
        // Proceed with form submission
    }
    
    // Close database connection
    mysqli_close($conn);
}

?>