What are the potential pitfalls of directly using data from HTML forms in SQL queries in PHP?

Directly using data from HTML forms in SQL queries in PHP can leave your application vulnerable to SQL injection attacks. To prevent this, you should always sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which helps prevent SQL injection by separating SQL code from user input.

// Assuming $conn is your database connection

// Sanitize and validate user input
$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 = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);

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

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

// Process the result as needed
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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