What are the potential pitfalls of directly using $_POST data in SQL queries in PHP?

Directly using $_POST data in SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To prevent this, it is important to sanitize and validate the input data before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which helps to separate the SQL logic from the user input.

// Sanitize and validate the input data
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();