What are common pitfalls when validating user input in PHP forms, specifically when checking for matching data in a MySQL database?

One common pitfall when validating user input in PHP forms, especially when checking for matching data in a MySQL database, is not sanitizing user input properly before querying the database. This can lead to SQL injection attacks. To solve this, always use prepared statements or parameterized queries to prevent SQL injection vulnerabilities.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check if the connection is successful
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);

// Prepare a statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Execute the statement
$stmt->execute();

// Get the result
$result = $stmt->get_result();

// Check if there is a matching username in the database
if ($result->num_rows > 0) {
    echo "Username already exists in the database.";
} else {
    echo "Username is available.";
}

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