What potential security risks are associated with directly inserting $_POST values into SQL code in PHP?

Directly inserting $_POST values into SQL code in PHP can lead to SQL injection attacks, where malicious users can manipulate the SQL query to execute unintended commands on the database. 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 separate the SQL code from the user input, preventing any malicious code injection.

// Assuming a connection to the database has been established

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

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

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

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}