What are the best practices for handling user input validation in PHP forms to prevent SQL injection vulnerabilities?

To prevent SQL injection vulnerabilities in PHP forms, it is essential to properly validate and sanitize user input before using it in SQL queries. One of the best practices is to use prepared statements with parameterized queries to securely handle user input. Additionally, using functions like mysqli_real_escape_string or PDO::quote can help sanitize input data and prevent malicious SQL injection attacks.

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Validate and sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Prepare and execute a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

// Process the query results
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    // User authentication successful
} else {
    // User authentication failed
}

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