What are the potential security risks of not properly filtering SQL statements in PHP when accessing user data?

The potential security risks of not properly filtering SQL statements in PHP when accessing user data include SQL injection attacks, where malicious SQL code is inserted into input fields to manipulate the database. To mitigate this risk, it is crucial to use prepared statements and parameterized queries to sanitize user input before executing SQL queries.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the sanitized user input to the placeholders
$stmt->bindParam(':username', $_POST['username']);

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

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

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